简体   繁体   English

使用readdir获取文件大小

[英]Getting file size using readdir

I am calling readdir() to get info from a directory for file names. 我正在调用readdir()从目录中获取文件名信息。 I also want to print the file sizes using readdir() only if possible as the structure of dirent is 我也只想在可能的情况下使用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 */
           };

I am using d_reclen as the file size but somehow my program prints wrong values. 我使用d_reclen作为文件大小,但是以某种方式我的程序打印了错误的值。 But my questions are : 但是我的问题是:

  1. Is it right to use d_reclen as the file size? 使用d_reclen作为文件大小是否正确? Because my doubt is that it is unsigned short and how can it return correct size for large files. 因为我怀疑它是短无符号的,对于大文件它如何返回正确的大小。
  2. What is actually length of record? 记录长度实际上是多少? Is this size in bytes? 这个大小以字节为单位吗? How can I calculate correct size? 如何计算正确的尺寸?

OUTPUT 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

EDIT 1 I am using printf("File size :%hu\\n",pent->d_reclen); 编辑1我正在使用printf("File size :%hu\\n",pent->d_reclen); to print file size but it is not giving the correct answer. 打印文件大小,但未给出正确答案。

EDIT 2 I want to avoid the usage of stat() for some performance reasons. 编辑2由于某些性能原因,我想避免使用stat()

The readdir manual says: readdir手册说:

 unsigned short d_reclen; /* length of this record */ 

"This record" is "this struct dirent instance", not "this file". “此记录”是“此struct dirent实例实例”,而不是“此文件”。

In your case ( d_reclne 20 or 24) you should not access the whole dirent memory, because readdir allocated only enough memory to fill in d_ino , d_off , d_reclen , d_type and the relevant parts of d_name . 在您的情况下( d_reclne 20或24),您不应访问整个dirent内存,因为readdir仅分配了足够的内存来填充d_inod_offd_reclend_typed_name的相关部分。 readdir did not allocate the complete 256 bytes for d_name . readdir没有为d_name分配完整的256个字节。

To get the file size, as opposed to the size (length) of the file name (which is what is recorded in d_reclen ), you need either the stat() or statat() (or lstat() ) system call. 要获得文件大小,而不是文件名的大小(长度)(这是d_reclen记录的大小),您需要stat()statat() (或lstat() )系统调用。 You can't get the file size directly from the information in struct dirent . 您不能直接从struct dirent的信息获取文件大小。

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

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