1

Normally I use the following code to determine the size of a file opened in fp in C:

size_t len;
fseek(fp, 0, SEEK_END);
len = ftell(fp);
rewind(fp);

The C Standard (§ 7.21.3, Files) has the following footnote:

Setting the file position indicator to end-of-file, as with fseek(file, 0, SEEK_END), has undefined behavior for a binary stream (because of possible trailing null characters) or for any stream with state-dependent encoding that does not assuredly end in the initial shift state.

I have not observed any cases myself where this method has failed to produce the correct size for a binary file in C code myself, but according to the standard it is not well defined unless (at least) the file is open in text mode.

The other methods I know of for determining a file size are platform-dependent (like the stat family of functions, and GetFileSize(Ex) on Windows).

Is there, then, any platform-independent way to determine the length of a FILE open in binary mode using only standard C functions?

Govind Parmar
  • 20,656
  • 7
  • 53
  • 85

0 Answers0