I am looking for some platform-independent C code to determine the size of a given file. First, I read the following answer: https://stackoverflow.com/a/238607
The answer uses fseek with SEEK_END and ftell. Now, my problem is that I found the following C standard quotes.
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.
and
A binary stream need not meaningfully support fseek calls with a whence value of SEEK_END.
So, it looks like I have a problem. Possibly, the following code, which counts the number of read bytes, is a workaround.
file = fopen(file_path, "rb");
/* ... */
while ( EOF != fgetc(file) ) {
ret = size_t_inc(&file_size_); /* essentially, this does ++file_size_ */
/* ... */
}
ret = feof(file);
/* ... */
if (!ret) {
return 1; /* Error! */
}
(entire function here: https://github.com/630R6/bytelev/blob/8e3d0dd14042f16086f3ca4e9a33d49a0629630e/main.c#L138)
Still, I am looking for a better solution.
Thanks so much for your time!