I have a simple function to print file size and file name:
void *mystat(void *filename) {
struct stat fileStat;
if (lstat(filename,&fileStat) < 0) {
fprintf(stderr, "no such file or directory: %s\n", filename);
return NULL;
}
printf(" %'d",fileStat.st_size);
printf(" %s\n", filename);
}
it works fine for small files, but when file is large (couple of GB) it prints size 0
.
Why is this not working for large files ?
EDIT
Actually it only prints file size 0
when the file size is multiple of 4GB
. In other case, when file is large but not multiple, it prints negative number.
but, when I capture the return code of lstat
and print it, it is 0
:
ret = lstat(filename,&fileStat)
I am compiling and running my code on a 64-bit system.
Obviously, the fileStat.st_size
is overflowing, but why?
lstat
is giving you the right answer. It's printf
that's the problem. Use %'ld
instead of %'d
to be good enough in practice, or if you want to be pedantically correct, then do this instead:
printf(" %'jd", (intmax_t)fileStat.st_size);
You may also need to #include <stdint.h>
, if you get an error that intmax_t
doesn't exist.