ptg10805159
Section 1.4 Files and Directories 7
the comments initalics.The dollar sign that precedes our input is the prompt that is
printed by the shell.We’ll always show the shell prompt as a dollar sign.
Note that the directory listing is not in alphabetical order.Thelscommand sorts
the names beforeprinting them.
Thereare many details to consider in this 20-line program.
•First, we include a header of our own:apue.h.Weinclude this header in almost
every program in this text. This header includes some standardsystem headers and
defines numerous constants and function prototypes that we use throughout the
examples in the text.Alisting of this header is in Appendix B.
•Next, we include a system header,dirent.h, to pick up the function prototypes for
opendirandreaddir, in addition to the definition of thedirentstructure. On
some systems, the definitions aresplit into multiple header files. For example, in the
Ubuntu 12.04 Linux distribution,/usr/include/dirent.hdeclares the function
prototypes and includesbits/dirent.h,which defines thedirentstructure(and
is actually stored in/usr/include/x86_64-linux-gnu/bits).
•The declaration of themain function uses the style supported by the ISO C
standard. (We’ll have more to say about the ISO C standard in the next chapter.)
•Wetake an argument from the command line,argv[1], as the name of the directory
to list. In Chapter 7, we’ll look at how themainfunction is called and how the
command-line arguments and environment variables areaccessible to the program.
•Because the actual format of directory entries varies from one UNIX system to
another, we use the functionsopendir,readdir,andclosedirto manipulate the
directory.
•Theopendirfunction returns a pointer to aDIRstructure, and we pass this pointer
to thereaddirfunction. Wedon’t carewhat’s in theDIRstructure. Wethen call
readdirin a loop, to read each directory entry.Thereaddirfunction returns a
pointer to adirentstructureor, when it’s finished with the directory,anull pointer.
All we examine in the dirent structure is the name of each directory entry
(d_name). Using this name, we could then call thestatfunction (Section 4.2) to
determine all the attributes of the file.
•Wecall two functions of our own to handle the errors:err_sysanderr_quit.We
can see from the preceding output that theerr_sysfunction prints an informative
message describing what type of error was encountered (‘‘Permission denied’’or
‘‘Not a directory’’). These two error functions areshown and described in
Appendix B.We also talk moreabout error handling in Section 1.7.
•When the program is done, it calls the functionexitwith an argument of 0. The
functionexitterminates a program. By convention, an argument of 0 means OK,
and an argument between 1 and 255 means that an error occurred. In Section 8.5, we
show how any program, such as a shell or a program that we write, can obtain the
exitstatus of a program that it executes.