How can I figure out the size of a file, in bytes?
#include <stdio.h>
unsigned int fsize(char* file){
//what goes here?
}
How can I figure out the size of a file, in bytes?
#include <stdio.h>
unsigned int fsize(char* file){
//what goes here?
}
If you're fine with using the std c library:
You can open the file, go to 0 offset relative from the bottom of the file with
the value returned from fseek is the size of the file.
I didn't code in C for a long time, but I think it should work.
And if you're building a Windows app, use the GetFileSizeEx API as CRT file I/O is messy, especially for determining file length, due to peculiarities in file representations on different systems ;)
Try this --
What this does is first, seek to the end of the file; then, report where the file pointer is. Lastly (this is optional) it rewinds back to the beginning of the file. Note that
fp
should be a binary stream.file_size contains the number of bytes the file contains. Note that since (according to climits.h) the unsigned long type is limited to 4294967295 bytes (4 gigabytes) you'll need to find a different variable type if you're likely to deal with files larger than that.
Looking at the question,
ftell
can easily get the number of bytes.Based on NilObject's code:
Changes:
const char
.struct stat
definition, which was missing the variable name.-1
on error instead of0
, which would be ambiguous for an empty file.off_t
is a signed type so this is possible.If you want
fsize()
to print a message on error, you can use this:On 32-bit systems you should compile this with the option
-D_FILE_OFFSET_BITS=64
, otherwiseoff_t
will only hold values up to 2 GB. See the "Using LFS" section of Large File Support in Linux for details.