Hello all,
I am pretty sure i asked this before but cannot remember when or how i did it.
Say i have file with a non constant number of integer per line.
1 2 3
4 5 6 7
is there a simple way of reading the data in array
i tried using this :
integer(4):: numberread(4)
!open file
open(newunit=fileunit,file='myfile',iostat = ioerror)
...
!read file
read(fileunit,*,iostat=ioerror) numberread
this read the first line and the first digit on the second line.
i also tried tris
read(fileunit,"(*(i))",iostat=ioerror) numberread
but this gave me an io error.
Thanks and kind regards
链接已复制
You could read the entire line as character(len=1024), or some number larger then the longest input line. Then use internal reads from that line for each number field, or count the delimiters to determine the number of values, then perform the internal read for the specific number of input variables.
Jim Dempsey
The way I would do this is:
- Read each line into a character variable, let's call it LINE
- LINE = TRIM(LINE) / " /"
- READ (LINE,*) numberread
This will leave undefined array elements that don't have corresponding values, as the slash terminates list-directed input. As an alternative, you can append " 0 0 0 0", which will supply zeroes for missing values. You may want to substitute something else.
Also: Please don't use literal KIND values (integer(4)). See Doctor Fortran in "It Takes All KINDs" - Doctor Fortran (stevelionel.com) for my thoughts on this. Consider adding IOSTAT= to the READ and test for a non-zero value in case of an input error.
Dear all, many thanks.
I did use the method suggested by @Steve_Lionel eventually.
Can i ask if it could have ben done using a format repetition or does the format repetition only woks with csv files ?
Fortran does not distinguish CSV files from other text files, but the point with CSV files is that the elements are separated by commas (or some other character) and you do not know the width of the element. That makes it difficult to use specific formats. Also the use of quotation marks (") or apostrophes (') to delimit strings, especially those with a space inside, makes it much easier to use list-directed reads (read(something,*)).
