4

My question is simple:

Should I use fseek with SEEK_END to get to the end of a file and then get the length of it ? Because in the man it is said:

  • Library implementations are allowed to not meaningfully support SEEK_END (therefore, code using it has no real standard portability).

Right now I am using stat (from C) which is better ?

dandan78
  • 13,328
  • 13
  • 64
  • 78
rXp
  • 617
  • 2
  • 12
  • 25
  • You mention `stat` and `man`, so is it safe to assume you are using Linux, or some other Unix? Do you care about other platforms? โ€“ BoBTFish Sep 27 '13 at 08:01
  • 2
    This question is good, but the way you phrased it makes it heavily opinion based and leads to discussions, which is not desirable. โ€“ Kevin Sep 27 '13 at 08:01
  • See https://www.securecoding.cert.org/confluence/display/seccode/FIO19-C.+Do+not+use+fseek%28%29+and+ftell%28%29+to+compute+the+size+of+a+regular+file. โ€“ Joseph Quinsey Feb 18 '14 at 15:22

2 Answers2

4

The ftell function returns a long, which means that on an ILP32 system you can't correctly get the size of a file larger than 2GB. You should use the stat function or similar to get the size of a file; check the manual for the operating system you're targeting in case you have use a different function name (stat64) or define a preprocessor macro to get the desired behavior for large files.

Joni
  • 108,737
  • 14
  • 143
  • 193
1

Since C++ inherits fseek and SEEK_END from C, I'm quoting the C standard here:

C11(ISO/IEC 9899:201x) ยง7.21.9.2 The fseek function section 3

A binary stream need not meaningfully support fseek calls with a whence value of SEEK_END.

Community
  • 1
  • 1
Yu Hao
  • 119,891
  • 44
  • 235
  • 294