问题描述
我想要的只是打印文件大小(以字节为单位)我正在使用
All i want is to print the size of a file in bytesI 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);
}
打印类型为off_t
的d_off是错误的.对于323,388 bytes
文件,它显示1296623584
The printing of the d_off that is type off_t
is wrong.For a file of 323,388 bytes
it prints 1296623584
我认为强制转换是问题所在.我尝试了很多类型的转换,例如%d
,%s
,%u
,%llu
...什么是正确的演员表?
I think that the casting is the problem. I tried lots of castings such as %d
, %s
,%u
, %llu
...What is the right casting?
用于查找文件大小的正确函数是使用统计结构的lstat()
.
The right function to use to find filesize is lstat()
using a stat struct.
推荐答案
正如@Andrey指出的那样,d_off的值并不总是有用的,甚至不存在.例如,OSX没有它.改用stat
呼叫.
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.
这篇关于从dirent结构中打印off_t文件大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!