Before flagging this as a duplicate, yes, I have read this:
How do you determine the size of a file in C?
I need to determine the size of files. The thing is - I need to do it portably in C. The answers in the above question use the POSIX stat
function.
Also, I cannot use fseek(f, 0, SEEK_END)
together with ftell(f)
as suggested. According to the C11 standard this is undefined behavior.
7.21.9.2:
A binary stream need not meaningfully support fseek calls with a whence value of SEEK_END.
The undefined behavior actually shows up on Windows (I didn't test it on Linux), and I learned this the hard way, in a bigger program. When running the same binary program on the same file, ftell()
sometimes returns -1
, sometimes the correct size and sometimes garbage values.
A solution I thought about is reading the entire file (until EOF
), byte by byte, and counting the number of bytes read. This could work, but it has some disadvantages that I would like to not have to deal with. Firstly, read errors could occur, and this would mess up the whole calculation. Secondly, reading a file byte by byte is slow, and normally, an operating system should be able to tell you the size of a file without even looking at its contents.
Is there any way to get the size of a file portably in C11?