How can I figure out the size of a file, in bytes?
#include
unsigned int fsize(char* file){
//what goes here?
}
The POSIX standard has its own method to get file size.
Include the sys/stat.h
header to use the function.
st_size
property.Note: It limits the size to 4GB
. If not Fat32
filesystem then use the 64bit version!
#include
#include
int main(int argc, char** argv)
{
struct stat info;
stat(argv[1], &info);
// 'st' is an acronym of 'stat'
printf("%s: size=%ld\n", argv[1], info.st_size);
}
#include
#include
int main(int argc, char** argv)
{
struct stat64 info;
stat64(argv[1], &info);
// 'st' is an acronym of 'stat'
printf("%s: size=%ld\n", argv[1], info.st_size);
}
The ANSI C doesn't directly provides the way to determine the length of the file.
We'll have to use our mind. For now, we'll use the seek approach!
#include
int main(int argc, char** argv)
{
FILE* fp = fopen(argv[1]);
int f_size;
fseek(fp, 0, SEEK_END);
f_size = ftell(fp);
rewind(fp); // to back to start again
printf("%s: size=%ld", (unsigned long)f_size);
}
If the file is
stdin
or a pipe. POSIX, ANSI C won't work.
It will going return0
if the file is a pipe orstdin
.Opinion: You should use POSIX standard instead. Because, it has 64bit support.