I can get the size of struct dirent precisely using sizeof operator。In my PC it printed 280.Its definition in dirent.h is as follows.
struct dirent
{
#ifndef __USE_FILE_OFFSET64
__ino_t d_ino;
__off_t d_off;
#else
__ino64_t d_ino;
__off64_t d_off;
#endif
unsigned short int d_reclen;
unsigned char d_type;
char d_name[256]; /* We must not include limits.h! */
};
It's correct.But I also noted that d_reclen is a member that shows the length of the record,it prints numbers like 24, 32, 40.etc. So in memeory, which one is the real size of the struct?
CodePudding user response:
The fact of sizeof()
showing 280, even if that reflects the real room for the struct in memory, is a don't care. Albeit d_name
is [256]
in this particular definition, POSIX defines it as d_name[]
, a character array of unspecified size. Depending on directory name size (shorter / longer), one indeed should be able to observe different values in d_reclen
, such as 24 or 32 in the above example.
Please see "The d_name field" section under "NOTES" in the man page.
The short of it, doing sizeof()
on d_name
is incorrect. Applications should either use d_reclen
or perform strlen()
on d_name
to know the name length.