fseek()/ftell() works sometimes.
if (fseek(fp, 0L, SEEK_END) != 0) printf("Size: %ld\n", ftell(fp)); }
Problems.
If the file size exceeds approximately LONG_MAX , the answer long int ftell(FILE *stream) problematic.
If the file is opened in text mode, the return value from ftell() may not match the length of the file. "For a text stream, the file position indicator contains undefined information," C11dr ยง7.21.9.4 2
If the file is opened in binary mode, fseek(fp, 0L, SEEK_END) is undefined. "Setting the file position indicator to the end of the file, like fseek(file, 0, SEEK_END) , has undefined behavior for the binary stream (due to possible terminating null characters) or for any stream with a state-dependent encoding that does not necessarily end in the initial state of shear. " C11dr footnote 268. @Evert This most often refers to earlier platforms than today, but is still part of the specification.
If the file is a stream as serial input or stdin , fseek(file, 0, SEEK_END) makes little sense.
The usual solution for finding file size is a non-portable platform. An example of a good @ dbush answer.
Note. If the code tries to allocate memory based on file size, the available memory can easily be exceeded by file size.
Due to these issues, I do not recommend this approach.
As a rule, the problem should be reworked so that you do not need to find the file size, but in order to increase the data as more input data is processed.
LL disclaimer: note that C spec footnotes are informative and therefore not necessarily normative.
chux
source share