Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Get binary file size in fortran (a solution)

Status
Not open for further replies.

anasso

Programmer
Jul 18, 2009
3
DK

In thread214-1248457, guillaume asked how to find
the size of a binary file in Fortran.

I had excactly the same problem, but could not find a portable solution to it on the internet, so I post mine here in the hope that Google will list it.

I made a binary search, using that the READ statement gives an error if you read past the end of file. If the read works fine, you know that the end of file is above the current record, else it's below.

A binary search like this on files less than 4 gigabytes only takes 32 iterations. Files up to 16 exabytes take 64 iterations, so it's not a very time consuming way to do it. It can, however, be done simpler if you go with a nonstandard way (like GNU FSTAT()).

The following code demonstrates how to make the search on files less than 4 gbyte. U is an unused file unit and FNAME is the file name.

INTEGER*8 FUNCTION FSIZE(U,FNAME)
IMPLICIT NONE
CHARACTER*(*) FNAME
INTEGER U, IOS
BYTE T
INTEGER*8 MAXLEN, START,ENDING, I

C Compile with 8 byte integers as default
C if you want to specify a larger MAXLEN
C than 2**32 - 1:
MAXLEN = 4294967295

C Open with record length 1:
OPEN(U, FILE=FNAME, STATUS='OLD', ACCESS='DIRECT',
+ FORM='UNFORMATTED', RECL=1)

C Binary search for file end.
C If we read fine, we're below file end,
C if we get an error, we're above file end.

START = 0
ENDING = MAXLEN

10 IF (ENDING - START .LE. 1) GOTO 30
I = (START + ENDING)/2
READ(U,REC=I,ERR=20,IOSTAT=IOS) T
C We read without error, so FSIZE .GE. I
START = I
GOTO 10

C Error encounted
20 IF (IOS .NE. 3) GOTO 99
C IOSTAT is 3, so EOF encountered, and FSIZE .LT. I
ENDING = I
GOTO 10

C Found the position of the last byte of the file
30 FSIZE = START

CLOSE(U)
RETURN
C Encounted another error than EOF:
99 FSIZE = -1
CLOSE(U)
RETURN
END

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top