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

read non fixed size array from a file


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 Kudos
5 Replies
Honored Contributor III

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 Kudos

you could try using non-advancing IO.  Try to read 4 items and use EOR and SIZE to detect if you only got 3.


0 Kudos
Honored Contributor III

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 ( 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 Kudos

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 Kudos
Honored Contributor I

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 Kudos