Silverfrost Forums

Welcome to our forums

Label error reading data from a file

20 May 2023 6:49 (Edited: 20 May 2023 1:17) #30335

Casus: a file is being read Relevant portions of the text, in the read file, begin and end with an * There are many such relevant portions

The keys are searched for by dataitem 'seek'. The keys are in one the first lines directly below the *'s, and nowhere else.

My question is: could this code be improved?

Patrick.

10 do while string(1:1).NE.'*') read(1,'(a)',iostat=stat)string end do read(1,'(a)',iostat=stat)string

if (index(string,seek(1:3)).NE.1)goto 10
	
		do while (string(1:1).NE.'*') 
		read(1,\'(a)\',iostat=stat)string
		print_*, string      !the program uses a subroutine to print
		end do
21 May 2023 10:29 #30338

Assuming the data file input.txt is

*
123
*
123
123, abc
*
123
123, abc
123
*
123
*

The following program:

program p
implicit none
integer fileopened, nlines, readstat, i
character(len=124) text
open(unit=10,file='input.txt', status='old', iostat=fileopened)
if (fileopened .ne. 0) stop 'Failed to open file existing file'
rewind 10
nlines = 0
do 
  read(unit=10,fmt='(A)',iostat=readstat) text
  if (readstat .eq. 0) then
    nlines = nlines + 1
    cycle
  else
    exit
  end if
end do
print'(a,1x,i3)', 'nlines = ', nlines
rewind 10
do i = 1, nlines
  read(unit=10,fmt='(A)') text
  if (index(text,'*') .eq. 1) then
    cycle
  else
    print*, trim(text)
  end if
end do
rewind 10
close(unit=10, status='keep')
end program p

Returns

nlines =   12
 123
 123
 123, abc
 123
 123, abc
 123
 123
Press RETURN to close window...

i.e. you read the file once to establish the number of lines in the file (nlines), then go back to the beginning of the file (rewind) and read and process each of the nlines in turn.

21 May 2023 3:12 #30339

Thank you, Kenneth, for your code. I was unable to respond before, for which my apologies. I have run your code. The casus as posted required text to be retrieved from an .exe file. The organisation of the text lines was in batches of lines (unequal numbers of lines). I call them labels. The first line of each label started with a single * as a delimiter of the label. Each * was followed by a key, identifying the contents of the focal label. I had posted code using a goto. This I thought wasn't very elegant. So the objective of my query was to improve the code, i.e., to do away with the goto statement. My impression is that i did not post my query clear enough. So it does not answer my query. Your code is also very much longer than my code. My code works and does so flawlessly, in spite of its ugliness. So we're having a nogo here.

Please login to reply.