![](/img/trans.png)
[英]golang os *File.Readdir using lstat on all files. Can it be optimised?
[英]Getting file size using readdir
我正在调用readdir()
从目录中获取文件名信息。 我也只想在可能的情况下使用readdir()
打印文件大小,因为dirent
的结构是
struct dirent {
ino_t d_ino; /* inode number */
off_t d_off; /* offset to the next dirent */
unsigned short d_reclen; /* length of this record */
unsigned char d_type; /* type of file; not supported
by all file system types */
char d_name[256]; /* filename */
};
我使用d_reclen
作为文件大小,但是以某种方式我的程序打印了错误的值。 但是我的问题是:
d_reclen
作为文件大小是否正确? 因为我怀疑它是短无符号的,对于大文件它如何返回正确的大小。 OUTPUT
Actual Size :1bytes File size :20
Actual Size :4bytes File size :20
Actual Size :8bytes File size :20
Actual Size :256bytes File size :20
Actual Size :0bytes File size :20
Actual Size :255bytes File size :20
Actual Size :1023bytes File size :24
编辑1我正在使用printf("File size :%hu\\n",pent->d_reclen);
打印文件大小,但未给出正确答案。
编辑2由于某些性能原因,我想避免使用stat()
。
readdir
手册说:
unsigned short d_reclen; /* length of this record */
“此记录”是“此struct dirent
实例实例”,而不是“此文件”。
在您的情况下( d_reclne
20或24),您不应访问整个dirent内存,因为readdir仅分配了足够的内存来填充d_ino
, d_off
, d_reclen
, d_type
和d_name
的相关部分。 readdir
没有为d_name
分配完整的256个字节。
要获得文件大小,而不是文件名的大小(长度)(这是d_reclen
记录的大小),您需要stat()
或statat()
(或lstat()
)系统调用。 您不能直接从struct dirent
的信息获取文件大小。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.