Fortranner
Fortranner

Reputation: 2605

Read line from file with padding in Fortran

If I have a text file where lines contains some non-blank characters followed by spaces, how do I read those lines into a character variable without excess spaces?

character (len=1000) :: text
open (unit=20,file="foo.txt",action="read")
read (20,"(a)") text

will read the first 1000 characters of a line into variable text, which will be padded with spaces at the end if there are fewer than 1000 characters in the line. But if the line length is 100 you have 900 extraneous spaces, and the program does not "know" how long the line read actually was.

Upvotes: 1

Views: 510

Answers (2)

gdupras
gdupras

Reputation: 751

character (len=1000) :: text
integer :: s, ios

open (unit=20,file="foo.txt",action="read")
read (20,"(a)", size=s, advance='no', iostat=ios) text

After that last line, s contains the number of characters read, including trailing spaces, which I think is what you wanted.

Notes:

With a size tag, you must also have an advance tag set to 'no' otherwise you get a compilation error. Since the format is "(a)", the whole line is read so the next read statement will advance to the next line despite the 'no'. That's fine.

ios stores a negative integer when attempting to read past the end of the line. This will always happen if the line is shorter than length of text. That's fine. When attempting to read past the end of the file, ios will store a different negative integer. What those two negative integers are is not set by the standard I think so you may have to experiment a bit. In my case, with the gfortran compiler, ios was -1 when attempting to read past the end of the file and -2 otherwise.

Upvotes: 0

Fortran strings are blank-padded. There is simply no chance to distinguish any significant blank-padding in your strings with constant-length Fortran strings.

If every whitespace character is important, I suggest to treat the file as a stream-access file instead (formated or unformatted as needed), read individual characters to some array buffer and allocate a deferred-length string only after you know the length you actually need.

Upvotes: 1

Related Questions