문제

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

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.

다른 팁

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?

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top