繁体   English   中英

使用readdir获取文件大小

[英]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作为文件大小,但是以某种方式我的程序打印了错误的值。 但是我的问题是:

  1. 使用d_reclen作为文件大小是否正确? 因为我怀疑它是短无符号的,对于大文件它如何返回正确的大小。
  2. 记录长度实际上是多少? 这个大小以字节为单位吗? 如何计算正确的尺寸?

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_inod_offd_reclend_typed_name的相关部分。 readdir没有为d_name分配完整的256个字节。

要获得文件大小,而不是文件名的大小(长度)(这是d_reclen记录的大小),您需要stat()statat() (或lstat() )系统调用。 您不能直接从struct dirent的信息获取文件大小。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM