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?
}
Matt's solution should work, except that it's C++ instead of C, and the initial tell shouldn't be necessary.
Fixed your brace for you, too. ;)
Update: This isn't really the best solution. It's limited to 4GB files on Windows and it's likely slower than just using a platform-specific call like
GetFileSizeEx
orstat64
.Don't use
int
. Files over 2 gigabytes in size are common as dirt these daysDon't use
unsigned int
. Files over 4 gigabytes in size are common as some slightly-less-common dirtIIRC the standard library defines
off_t
as an unsigned 64 bit integer, which is what everyone should be using. We can redefine that to be 128 bits in a few years when we start having 16 exabyte files hanging around.If you're on windows, you should use GetFileSizeEx - it actually uses a signed 64 bit integer, so they'll start hitting problems with 8 exabyte files. Foolish Microsoft! :-)
Here's a simple and clean function that returns the file size.
You're going to need to use a library function to retrieve the details of a file. As C is completely platform independent, you're going to need to let us know what platform / operating system you're developing for!
I used this set of code to find the file length.
**Don't do this (why?):
Change the definition to int so that error messages can be transmitted, and then use fseek() and ftell() to determine the file size.