Printing off_t file size from dirent struct

5.7k views Asked by At

All i want is to print the size of a file in bytes I am using

DIR *d;
struct dirent *dir;
d= opendir(absolute_path);

while((dir= readdir(d))!=NULL){
    printf("%s\t %d\t %u\n",dir->d_name,dir->d_type,(int long long )dir->d_off);
}

The printing of the d_off that is type off_t is wrong. For a file of 323,388 bytes it prints 1296623584

I think that the casting is the problem. I tried lots of castings such as %d , %s,%u, %llu... What is the right casting?

EDIT: The right function to use to find filesize is lstat() using a stat struct.

2

There are 2 answers

2
Sean Perry On BEST ANSWER

As @Andrey points out, the value of d_off is not always useful or even present. OSX does not have it for instance. Use a call to stat instead.

0
Andrey Mishchenko On

From the readdir man page:

Only the fields d_name and d_ino are specified in POSIX.1-2001. The remaining fields are available on many, but not all systems. Under glibc, programs can check for the availability of the fields not defined in POSIX.1 by testing whether the macros _DIRENT_HAVE_D_NAMLEN, _DIRENT_HAVE_D_RECLEN, _DIRENT_HAVE_D_OFF, or _DIRENT_HAVE_D_TYPE are defined.

The value returned in d_off is the same as would be returned by calling telldir(3) at the current position in the directory stream. Be aware that despite its type and name, the d_off field is seldom any kind of directory offset on modern filesystems. Applications should treat this field as an opaque value, making no assumptions about its contents; see also telldir(3).

To find a file's size, see How do you determine the size of a file in C?