I am confused by the use of d_name[256]
and NAME_MAX
in struct dirent definition. Does d_name[256]
mean that the filename length can be atmost 256 character? Then it also mentions NAME_MAX (quoted in the bottom). So, my question is how NAME_MAX
relates here and where can I find NAME_MAX
value and definition?
In man readdir
struct dirent
is defined as following.
struct dirent {
ino_t d_ino; /* inode number */
off_t d_off; /* not an offset; see NOTES */
unsigned short d_reclen; /* length of this record */
unsigned char d_type; /* type of file; not supported
by all filesystem types */
char d_name[256]; /* filename */
};
It also asserts that
The only fields in the dirent structure that are mandated by POSIX.1 are:
d_name[]
, of unspecified size, with at mostNAME_MAX
characters preceding the terminating null byte ('\0'); and (as an XSI exten‐ sion)d_ino
. The other fields are unstandardized, and not present on all systems; see NOTES below for some further details.
NAME_MAX
is declared in limits.h
. You can also use pathconf()
or fpathconf()
to get the per-filesystem limit.
long max = pathconf(pathname, _PC_NAME_MAX);
Since the structure has this hard-coded to 256
, it can't actually handle filesystems with longer filenames. So NAME_MAX
will necessarily be at most 255
(which is indeed its value on my OS X machine).