[英]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 : 但是我的问题是:
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. 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_ino
, d_off
, d_reclen
, d_type
和d_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.