Printing off_t file size from dirent struct

折月煮酒 提交于 2019-12-11 03:35:34

问题


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.


回答1:


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.




回答2:


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?



来源:https://stackoverflow.com/questions/20528616/printing-off-t-file-size-from-dirent-struct

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!