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

Determining file length

alexismor
Beginner
428 Views
Hi everyone,

I was wondering if there was an easy way to do this. I wan't to read some data from a file, and input it into an allocatable matrix. To do this I need to know how many lines there are in the file, so that I can allocate the right size to the matrix.

For example, suppose that I have a file called data.dat which has the following data:

1 2 3
4 5 6
7 8 9

I would like to know that there are 3 lines, so that I can allocate my array appropriately. Is there an easy way to do this?

Thanks,

Alexis
0 Kudos
3 Replies
Steven_L_Intel1
Employee
428 Views
It's pretty easy to get how many bytes are in a file (GETFILEINFOQQ). But "lines"? unless you know that each line is the same number of bytes, you will have to read through the file and count the lines yourself.

Most applications like this require that the size of the data be specified in a prior record first.
0 Kudos
jim_dempsey
Beginner
428 Views

Or in a final last record.

e.g. FileSize-n bytes is a record containing

Signature

File information (array dimensions in this case)

The Signature is used to verify if the file is corrupt.

Jim Dempsey

0 Kudos
cacciatore
Beginner
428 Views

Alexis
By the example you gave:

1 2 3

4 5 6

7 8 9

it seems to be a sequential formatted ASCII file. In this case I use:

open(unit=3, file='data.txt',form='formatted')
nlines=0
do while(.not.eof(3))
read(3,*)
nlines=nlines+1
end do
rewind(3)
allocate(matrix(nlines,...))
do i=1,nlines
read(3,fmt='....')matrix(i,..)
end do

Don't know if read(3,*) would work with binary sequential files.

Geraldo

0 Kudos
Reply