When you have a pointer to a FILE structure, what's the standard way of determining the size (in bytes) of the open file?
Name:
Anonymous2010-05-29 15:49
Read'em and count, you lazy bastard.
Name:
Anonymous2010-05-29 15:51
Does sizeof work in this case?
Name:
Anonymous2010-05-29 16:03
yes.
Name:
Anonymous2010-05-29 16:03
Use fseek to position the file pointer at the end of the file, then get the position using ftell and finally use fseek or rewind to position the file pointer back at the start.
ftell returns the offset as a long int, so it may fail on files whose sizes cannot be represented as a long int.
>>1 fstat or fseek+ftell. >>3
Don't be silly. sizeof is for seeing how much storage a concrete variable needs. It's a compile time operator (the value is known at compile time), and thus it wouldn't work for such purposes.
>>8
The alternative to fseek/ftell is to read the whole file until you get an EOF. The OP did after all ask how to do it in C, not how to do it in POSIX or ENTERPRISE BULLSHITE.
>>8
There's also the problem of race conditions in multi-threaded environments. You'd have to lock the FILE object, get the current position, seek to end, get position, seek to current position, and exit the lock. However, I've used fseek+ftell+rewind quite a few times mostly for writing simple tools operating on binary files. There's no risk for those cases.
A binary stream need not meaningfully support fseek calls with a whence value of SEEK_END.
Except for the fact that nearly every fucking implementation out there will correctly do this.
>>16
Then fseek will fail and either the code wasn't designed for unbounded streams or the user is an idiot for trying to use one with it.
Name:
Anonymous2010-05-30 2:03
if you use fstat, make sure you use st_blksize and st_blocks to get the size, since st_size can overflow. if off_t is 32 bits, it'll overflow at 4GB. if off_t is 64 bits, it'll overflow at 16EB.