I am calling readdir()
to get info from a directory for file names. I also want to print the file sizes using readdir()
only if possible as the structure of dirent
is
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. But my questions are :
d_reclen
as the file size? Because my doubt is that it is unsigned short and how can it return correct size for large files. 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);
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.
The readdir
manual says:
unsigned short d_reclen; /* length of this record */
"This record" is "this struct dirent
instance", not "this file".
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
. readdir
did not allocate the complete 256 bytes for d_name
.
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. You can't get the file size directly from the information in struct dirent
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.