Query about <dirent.h>

gwyn at BRL.MIL gwyn at BRL.MIL
Tue Nov 28 08:38:14 AEST 1989


From: gwyn at BRL.MIL

In article <444 at longway.TIC.COM> Andy Tanenbaum <uunet!cs.vu.nl!ast> writes:
>In article <442 at longway.TIC.COM> gwyn at brl.arpa (Doug Gwyn) writes:
>>That's what happens when programmers assume things that are not promised
>>by the standards.
>I don't follow.  What is it that that the standards don't promise.

>From IEEE Std 1003.1-1988: "The character array d_name is of unspecified size".

>Surely a programmer may declare a struct dirent, ...

Sure, but that doesn't mean that it will be particularly useful to do so.

>Furthermore, a programmer may assume that d_name is an array of characters
>that can hold a file name.

That is the important thing that is NOT promised by the standard.
d_name must have type char[] and the filename that it represents
must be null terminated, with no more than NAME_MAX bytes before
the null terminator.

>I don't see how you can put a file name in 1 character.  I don't see any
>alternative than to allocate NAME_MAX+1 characters there.

Because it is wasteful to allocate so much storage for what are typically
short strings, many (maybe even most) implementations allocate just as
much as is actually needed for each individual struct dirent (including
possibly a few bytes for alignment).  Practically all C compilers support
this kind of "type punning", but the programmer need to be careful not to
make unwarranted assumptions.

The reason the standard does not specify char d_name[NAME_MAX+1] is
precisely to allow this particular implementation technique.

>Why doesn't the standard require <dirent.h> to have <limits.h> as a
>prerequisite, so that NAME_MAX is at least known.

IEEE Std 1003.1-1988 explains how a programmer who wished to obtain
that information may do so.  Since the implementation of <dirent.h>
does not require the macro NAME_MAX, it would have been pretty silly
to have required <limits.h> to be included before <dirent.h>.

Volume-Number: Volume 17, Number 74



More information about the Comp.std.unix mailing list