Search code examples
cbuffer-overflowstaterrno

st_size is negative but there is no error


This is the code I use to display the size of the file "myfile_name"

struct stat stbuf;
if (stat("myfile_name",&stbuf)<0) {
    fprintf(stderr, "\nError : %s \nErrno : %s","stat_big file",strerror(errno));
}

printf("ST_SIZE : %ld",stbuf.st_size);

st_size = -1509949440 (bytes) when the size of the file is 2,785,017,856 bytes (2.5)

I have searched for many hours for the solution, I have tried to add this line: #define _FILE_OFFSET_BITS 64 but it didn't work. errno tells me that there is no error. Apparently, for the stat function, there is no overflow. In another question the answer was to use %ld because of the type of stbuf.st_size (off_t) but it doesn't work.

The code works perfectly with small files.


Solution

  • The %ld format specifier expects an argument of type (signed) long, but stbuf.st_size has type off_t. There is no format specifier for off_t. Instead you need to cast to a type that can hold any value in the range of off_t and for which you have a format specifier. For example:

    printf("%lld\n", (long long)stbuf.st_size);
    

    or even better:

    printf("%jd\n", (intmax_t)stbuf.st_size);