Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Reading a Text File

Status
Not open for further replies.

gjw1684

Vendor
May 26, 2007
9
US
Good afternoon,

I have a question regarding reading from a text file. Suppose that I have a text file that looks like:

10003 343 0.04 1213 ES1(10-1) 3454 34
10024 342 0.93 1212 ES2(9-2) 3452 34 245 34
10032 331 1.44 1880 MT1(7-6) 2323 21 354 111 345
...
...
...

This text file can go up to 100 rows and each of these rows are not necessarily of the same length. What I would like to do is to read the text file, search for the occurrence of a particular phrase (e.g. "ES1" or "MT1"), and then output the row that contains that phrase. I originally attempted to put each line into an array, but since these rows are uneven, this didn't work properly. Any suggestions?
 
The possible solution depends on Fortran and compiler versions. For example, Silverstone FTN95 contains a proper set of character manipulation routines. In F77 you must write your own search substring function...
 
Hi gjw1684

Program xxx
character*256 str
character*3 phrase
phrase = 'ES1'
open(unit=1,file='text.txt',status='old')
do while(.true.)
read (1,'(a)',end=99) str
n = len_trim(str)
k = index(str(1:n),phrase)
if(k.ne.0) then
write(*,'(1x,a)') str
endif
enddo
99 continue
end

Bye, bye

 
I checked the code and it works. Thanks gullipe.

 
Hello again, I have another question

Consider the same type of text file


19.9 4473.5 0.601 0.562 26495.581 0.554 46652.1 86 32
20.1 3332.3 0.602 0.232 232943.439203 0.23 134.1 34 56
84.24 442034.5 0.124 0.321 304202.323 0.32 0.00324 392030
...
...

This has an unknown number of rows with an uneven amount of columns. What I would like to do is to look at the 7th column of each row, check to see if that number is less than 0.234, and print out that row to a text file.

My first guess to do this was to treat each row as a character string and to use a substring to pull out the 7th column. However, since there are an even number of columns, I will get incorrect results for a large number of rows. Any suggestions
 
Try this approach:
Code:
character(len=256)::s
integer a(256)
integer n
...
! input loop here
read(*,fmt='(A)',end=777) s ! 777 - end of file
read(s,*,end=555,err=666) (a(n),n=1,256)
! more than 256 integers - impossible
555 n = n - 1 ! n - number of columns
if (n .lt. 7) ! less than 7 columns
...
if (a(7) .lt. 0.234) ! output s
...
! end of loop
...
666 ... ! not a number in the line
...
777 ... ! all done
...
 
Sorry, use double precision or real (not integer) array for input.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top