Intel® Fortran Compiler
Build applications that can scale for the future with optimized code designed for Intel® Xeon® and compatible processors.

read non fixed size array from a file

Le_Callet__Morgan_M
1,045 次查看

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

 

0 项奖励
5 回复数
jimdempseyatthecove
名誉分销商 III
1,030 次查看

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

0 项奖励
Ron_Green
主持人
1,023 次查看

you could try using non-advancing IO.  Try to read 4 items and use EOR and SIZE to detect if you only got 3.  http://ahamodel.uib.no/intel/GUID-693D25E1-A2F6-402D-A353-D87C69E72DC9.html

 

0 项奖励
Steve_Lionel
名誉分销商 III
1,005 次查看

The way I would do this is:

  1. Read each line into a character variable, let's call it LINE
  2. LINE = TRIM(LINE) / " /"
  3. 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.

0 项奖励
Le_Callet__Morgan_M
940 次查看

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 ?

0 项奖励
Arjen_Markus
名誉分销商 II
925 次查看

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,*)).

0 项奖励
回复