This is Info file libc.info, produced by Makeinfo version 1.68 from the
input file libc.texinfo.

INFO-DIR-SECTION GNU libraries
START-INFO-DIR-ENTRY
* Libc: (libc).                 C library.
END-INFO-DIR-ENTRY

   This file documents the GNU C library.

   This is Edition 0.08 DRAFT, last updated 11 Jan 1999, of `The GNU C
Library Reference Manual', for Version 2.1 Beta.

   Copyright (C) 1993, '94, '95, '96, '97, '98, '99 Free Software
Foundation, Inc.

   Permission is granted to make and distribute verbatim copies of this
manual provided the copyright notice and this permission notice are
preserved on all copies.

   Permission is granted to copy and distribute modified versions of
this manual under the conditions for verbatim copying, provided also
that the section entitled "GNU Library General Public License" is
included exactly as in the original, and provided that the entire
resulting derived work is distributed under the terms of a permission
notice identical to this one.

   Permission is granted to copy and distribute translations of this
manual into another language, under the above conditions for modified
versions, except that the text of the translation of the section
entitled "GNU Library General Public License" must be approved for
accuracy by the Foundation.


File: libc.info,  Node: File Status Flags,  Next: File Locks,  Prev: Descriptor Flags,  Up: Low-Level I/O

File Status Flags
=================

   "File status flags" are used to specify attributes of the opening of
a file.  Unlike the file descriptor flags discussed in *Note Descriptor
Flags::, the file status flags are shared by duplicated file descriptors
resulting from a single opening of the file.  The file status flags are
specified with the FLAGS argument to `open'; *note Opening and Closing
Files::..

   File status flags fall into three categories, which are described in
the following sections.

   * *Note Access Modes::, specify what type of access is allowed to the
     file: reading, writing, or both.  They are set by `open' and are
     returned by `fcntl', but cannot be changed.

   * *Note Open-time Flags::, control details of what `open' will do.
     These flags are not preserved after the `open' call.

   * *Note Operating Modes::, affect how operations such as `read' and
     `write' are done.  They are set by `open', and can be fetched or
     changed with `fcntl'.

   The symbols in this section are defined in the header file `fcntl.h'.

* Menu:

* Access Modes::                Whether the descriptor can read or write.
* Open-time Flags::             Details of `open'.
* Operating Modes::             Special modes to control I/O operations.
* Getting File Status Flags::   Fetching and changing these flags.


File: libc.info,  Node: Access Modes,  Next: Open-time Flags,  Up: File Status Flags

File Access Modes
-----------------

   The file access modes allow a file descriptor to be used for reading,
writing, or both.  (In the GNU system, they can also allow none of
these, and allow execution of the file as a program.)  The access modes
are chosen when the file is opened, and never change.

 - Macro: int O_RDONLY
     Open the file for read access.

 - Macro: int O_WRONLY
     Open the file for write access.

 - Macro: int O_RDWR
     Open the file for both reading and writing.

   In the GNU system (and not in other systems), `O_RDONLY' and
`O_WRONLY' are independent bits that can be bitwise-ORed together, and
it is valid for either bit to be set or clear.  This means that
`O_RDWR' is the same as `O_RDONLY|O_WRONLY'.  A file access mode of
zero is permissible; it allows no operations that do input or output to
the file, but does allow other operations such as `fchmod'.  On the GNU
system, since "read-only" or "write-only" is a misnomer, `fcntl.h'
defines additional names for the file access modes.  These names are
preferred when writing GNU-specific code.  But most programs will want
to be portable to other POSIX.1 systems and should use the POSIX.1
names above instead.

 - Macro: int O_READ
     Open the file for reading.  Same as `O_RDWR'; only defined on GNU.

 - Macro: int O_WRITE
     Open the file for reading.  Same as `O_WRONLY'; only defined on
     GNU.

 - Macro: int O_EXEC
     Open the file for executing.  Only defined on GNU.

   To determine the file access mode with `fcntl', you must extract the
access mode bits from the retrieved file status flags.  In the GNU
system, you can just test the `O_READ' and `O_WRITE' bits in the flags
word.  But in other POSIX.1 systems, reading and writing access modes
are not stored as distinct bit flags.  The portable way to extract the
file access mode bits is with `O_ACCMODE'.

 - Macro: int O_ACCMODE
     This macro stands for a mask that can be bitwise-ANDed with the
     file status flag value to produce a value representing the file
     access mode.  The mode will be `O_RDONLY', `O_WRONLY', or `O_RDWR'.
     (In the GNU system it could also be zero, and it never includes the
     `O_EXEC' bit.)


File: libc.info,  Node: Open-time Flags,  Next: Operating Modes,  Prev: Access Modes,  Up: File Status Flags

Open-time Flags
---------------

   The open-time flags specify options affecting how `open' will behave.
These options are not preserved once the file is open.  The exception to
this is `O_NONBLOCK', which is also an I/O operating mode and so it
*is* saved.  *Note Opening and Closing Files::, for how to call `open'.

   There are two sorts of options specified by open-time flags.

   * "File name translation flags" affect how `open' looks up the file
     name to locate the file, and whether the file can be created.

   * "Open-time action flags" specify extra operations that `open' will
     perform on the file once it is open.

   Here are the file name translation flags.

 - Macro: int O_CREAT
     If set, the file will be created if it doesn't already exist.

 - Macro: int O_EXCL
     If both `O_CREAT' and `O_EXCL' are set, then `open' fails if the
     specified file already exists.  This is guaranteed to never
     clobber an existing file.

 - Macro: int O_NONBLOCK
     This prevents `open' from blocking for a "long time" to open the
     file.  This is only meaningful for some kinds of files, usually
     devices such as serial ports; when it is not meaningful, it is
     harmless and ignored.  Often opening a port to a modem blocks
     until the modem reports carrier detection; if `O_NONBLOCK' is
     specified, `open' will return immediately without a carrier.

     Note that the `O_NONBLOCK' flag is overloaded as both an I/O
     operating mode and a file name translation flag.  This means that
     specifying `O_NONBLOCK' in `open' also sets nonblocking I/O mode;
     *note Operating Modes::..  To open the file without blocking but
     do normal I/O that blocks, you must call `open' with `O_NONBLOCK'
     set and then call `fcntl' to turn the bit off.

 - Macro: int O_NOCTTY
     If the named file is a terminal device, don't make it the
     controlling terminal for the process.  *Note Job Control::, for
     information about what it means to be the controlling terminal.

     In the GNU system and 4.4 BSD, opening a file never makes it the
     controlling terminal and `O_NOCTTY' is zero.  However, other
     systems may use a nonzero value for `O_NOCTTY' and set the
     controlling terminal when you open a file that is a terminal
     device; so to be portable, use `O_NOCTTY' when it is important to
     avoid this.

   The following three file name translation flags exist only in the
GNU system.

 - Macro: int O_IGNORE_CTTY
     Do not recognize the named file as the controlling terminal, even
     if it refers to the process's existing controlling terminal
     device.  Operations on the new file descriptor will never induce
     job control signals.  *Note Job Control::.

 - Macro: int O_NOLINK
     If the named file is a symbolic link, open the link itself instead
     of the file it refers to.  (`fstat' on the new file descriptor will
     return the information returned by `lstat' on the link's name.)

 - Macro: int O_NOTRANS
     If the named file is specially translated, do not invoke the
     translator.  Open the bare file the translator itself sees.

   The open-time action flags tell `open' to do additional operations
which are not really related to opening the file.  The reason to do them
as part of `open' instead of in separate calls is that `open' can do
them atomically.

 - Macro: int O_TRUNC
     Truncate the file to zero length.  This option is only useful for
     regular files, not special files such as directories or FIFOs.
     POSIX.1 requires that you open the file for writing to use
     `O_TRUNC'.  In BSD and GNU you must have permission to write the
     file to truncate it, but you need not open for write access.

     This is the only open-time action flag specified by POSIX.1.
     There is no good reason for truncation to be done by `open',
     instead of by calling `ftruncate' afterwards.  The `O_TRUNC' flag
     existed in Unix before `ftruncate' was invented, and is retained
     for backward compatibility.

   The remaining operating modes are BSD extensions.  They exist only
on some systems.  On other systems, these macros are not defined.

 - Macro: int O_SHLOCK
     Acquire a shared lock on the file, as with `flock'.  *Note File
     Locks::.

     If `O_CREAT' is specified, the locking is done atomically when
     creating the file.  You are guaranteed that no other process will
     get the lock on the new file first.

 - Macro: int O_EXLOCK
     Acquire an exclusive lock on the file, as with `flock'.  *Note
     File Locks::.  This is atomic like `O_SHLOCK'.


File: libc.info,  Node: Operating Modes,  Next: Getting File Status Flags,  Prev: Open-time Flags,  Up: File Status Flags

I/O Operating Modes
-------------------

   The operating modes affect how input and output operations using a
file descriptor work.  These flags are set by `open' and can be fetched
and changed with `fcntl'.

 - Macro: int O_APPEND
     The bit that enables append mode for the file.  If set, then all
     `write' operations write the data at the end of the file, extending
     it, regardless of the current file position.  This is the only
     reliable way to append to a file.  In append mode, you are
     guaranteed that the data you write will always go to the current
     end of the file, regardless of other processes writing to the
     file.  Conversely, if you simply set the file position to the end
     of file and write, then another process can extend the file after
     you set the file position but before you write, resulting in your
     data appearing someplace before the real end of file.

 - Macro: int O_NONBLOCK
     The bit that enables nonblocking mode for the file.  If this bit
     is set, `read' requests on the file can return immediately with a
     failure status if there is no input immediately available, instead
     of blocking.  Likewise, `write' requests can also return
     immediately with a failure status if the output can't be written
     immediately.

     Note that the `O_NONBLOCK' flag is overloaded as both an I/O
     operating mode and a file name translation flag; *note Open-time
     Flags::..

 - Macro: int O_NDELAY
     This is an obsolete name for `O_NONBLOCK', provided for
     compatibility with BSD.  It is not defined by the POSIX.1 standard.

   The remaining operating modes are BSD and GNU extensions.  They
exist only on some systems.  On other systems, these macros are not
defined.

 - Macro: int O_ASYNC
     The bit that enables asynchronous input mode.  If set, then `SIGIO'
     signals will be generated when input is available.  *Note
     Interrupt Input::.

     Asynchronous input mode is a BSD feature.

 - Macro: int O_FSYNC
     The bit that enables synchronous writing for the file.  If set,
     each `write' call will make sure the data is reliably stored on
     disk before returning.  Synchronous writing is a BSD feature.

 - Macro: int O_SYNC
     This is another name for `O_FSYNC'.  They have the same value.

 - Macro: int O_NOATIME
     If this bit is set, `read' will not update the access time of the
     file.  *Note File Times::.  This is used by programs that do
     backups, so that backing a file up does not count as reading it.
     Only the owner of the file or the superuser may use this bit.

     This is a GNU extension.


File: libc.info,  Node: Getting File Status Flags,  Prev: Operating Modes,  Up: File Status Flags

Getting and Setting File Status Flags
-------------------------------------

   The `fcntl' function can fetch or change file status flags.

 - Macro: int F_GETFL
     This macro is used as the COMMAND argument to `fcntl', to read the
     file status flags for the open file with descriptor FILEDES.

     The normal return value from `fcntl' with this command is a
     nonnegative number which can be interpreted as the bitwise OR of
     the individual flags.  Since the file access modes are not
     single-bit values, you can mask off other bits in the returned
     flags with `O_ACCMODE' to compare them.

     In case of an error, `fcntl' returns -1.  The following `errno'
     error conditions are defined for this command:

    `EBADF'
          The FILEDES argument is invalid.

 - Macro: int F_SETFL
     This macro is used as the COMMAND argument to `fcntl', to set the
     file status flags for the open file corresponding to the FILEDES
     argument.  This command requires a third `int' argument to specify
     the new flags, so the call looks like this:

          fcntl (FILEDES, F_SETFL, NEW-FLAGS)

     You can't change the access mode for the file in this way; that is,
     whether the file descriptor was opened for reading or writing.

     The normal return value from `fcntl' with this command is an
     unspecified value other than -1, which indicates an error.  The
     error conditions are the same as for the `F_GETFL' command.

   If you want to modify the file status flags, you should get the
current flags with `F_GETFL' and modify the value.  Don't assume that
the flags listed here are the only ones that are implemented; your
program may be run years from now and more flags may exist then.  For
example, here is a function to set or clear the flag `O_NONBLOCK'
without altering any other flags:

     /* Set the `O_NONBLOCK' flag of DESC if VALUE is nonzero,
        or clear the flag if VALUE is 0.
        Return 0 on success, or -1 on error with `errno' set. */
     
     int
     set_nonblock_flag (int desc, int value)
     {
       int oldflags = fcntl (desc, F_GETFL, 0);
       /* If reading the flags failed, return error indication now. */
       if (oldflags == -1)
         return -1;
       /* Set just the flag we want to set. */
       if (value != 0)
         oldflags |= O_NONBLOCK;
       else
         oldflags &= ~O_NONBLOCK;
       /* Store modified flag word in the descriptor. */
       return fcntl (desc, F_SETFL, oldflags);
     }


File: libc.info,  Node: File Locks,  Next: Interrupt Input,  Prev: File Status Flags,  Up: Low-Level I/O

File Locks
==========

   The remaining `fcntl' commands are used to support "record locking",
which permits multiple cooperating programs to prevent each other from
simultaneously accessing parts of a file in error-prone ways.

   An "exclusive" or "write" lock gives a process exclusive access for
writing to the specified part of the file.  While a write lock is in
place, no other process can lock that part of the file.

   A "shared" or "read" lock prohibits any other process from
requesting a write lock on the specified part of the file.  However,
other processes can request read locks.

   The `read' and `write' functions do not actually check to see
whether there are any locks in place.  If you want to implement a
locking protocol for a file shared by multiple processes, your
application must do explicit `fcntl' calls to request and clear locks
at the appropriate points.

   Locks are associated with processes.  A process can only have one
kind of lock set for each byte of a given file.  When any file
descriptor for that file is closed by the process, all of the locks
that process holds on that file are released, even if the locks were
made using other descriptors that remain open.  Likewise, locks are
released when a process exits, and are not inherited by child processes
created using `fork' (*note Creating a Process::.).

   When making a lock, use a `struct flock' to specify what kind of
lock and where.  This data type and the associated macros for the
`fcntl' function are declared in the header file `fcntl.h'.

 - Data Type: struct flock
     This structure is used with the `fcntl' function to describe a file
     lock.  It has these members:

    `short int l_type'
          Specifies the type of the lock; one of `F_RDLCK', `F_WRLCK',
          or `F_UNLCK'.

    `short int l_whence'
          This corresponds to the WHENCE argument to `fseek' or
          `lseek', and specifies what the offset is relative to.  Its
          value can be one of `SEEK_SET', `SEEK_CUR', or `SEEK_END'.

    `off_t l_start'
          This specifies the offset of the start of the region to which
          the lock applies, and is given in bytes relative to the point
          specified by `l_whence' member.

    `off_t l_len'
          This specifies the length of the region to be locked.  A
          value of `0' is treated specially; it means the region
          extends to the end of the file.

    `pid_t l_pid'
          This field is the process ID (*note Process Creation
          Concepts::.) of the process holding the lock.  It is filled
          in by calling `fcntl' with the `F_GETLK' command, but is
          ignored when making a lock.

 - Macro: int F_GETLK
     This macro is used as the COMMAND argument to `fcntl', to specify
     that it should get information about a lock.  This command
     requires a third argument of type `struct flock *' to be passed to
     `fcntl', so that the form of the call is:

          fcntl (FILEDES, F_GETLK, LOCKP)

     If there is a lock already in place that would block the lock
     described by the LOCKP argument, information about that lock
     overwrites `*LOCKP'.  Existing locks are not reported if they are
     compatible with making a new lock as specified.  Thus, you should
     specify a lock type of `F_WRLCK' if you want to find out about both
     read and write locks, or `F_RDLCK' if you want to find out about
     write locks only.

     There might be more than one lock affecting the region specified
     by the LOCKP argument, but `fcntl' only returns information about
     one of them.  The `l_whence' member of the LOCKP structure is set
     to `SEEK_SET' and the `l_start' and `l_len' fields set to identify
     the locked region.

     If no lock applies, the only change to the LOCKP structure is to
     update the `l_type' to a value of `F_UNLCK'.

     The normal return value from `fcntl' with this command is an
     unspecified value other than -1, which is reserved to indicate an
     error.  The following `errno' error conditions are defined for
     this command:

    `EBADF'
          The FILEDES argument is invalid.

    `EINVAL'
          Either the LOCKP argument doesn't specify valid lock
          information, or the file associated with FILEDES doesn't
          support locks.

 - Macro: int F_SETLK
     This macro is used as the COMMAND argument to `fcntl', to specify
     that it should set or clear a lock.  This command requires a third
     argument of type `struct flock *' to be passed to `fcntl', so that
     the form of the call is:

          fcntl (FILEDES, F_SETLK, LOCKP)

     If the process already has a lock on any part of the region, the
     old lock on that part is replaced with the new lock.  You can
     remove a lock by specifying a lock type of `F_UNLCK'.

     If the lock cannot be set, `fcntl' returns immediately with a value
     of -1.  This function does not block waiting for other processes
     to release locks.  If `fcntl' succeeds, it return a value other
     than -1.

     The following `errno' error conditions are defined for this
     function:

    `EAGAIN'
    `EACCES'
          The lock cannot be set because it is blocked by an existing
          lock on the file.  Some systems use `EAGAIN' in this case,
          and other systems use `EACCES'; your program should treat
          them alike, after `F_SETLK'.  (The GNU system always uses
          `EAGAIN'.)

    `EBADF'
          Either: the FILEDES argument is invalid; you requested a read
          lock but the FILEDES is not open for read access; or, you
          requested a write lock but the FILEDES is not open for write
          access.

    `EINVAL'
          Either the LOCKP argument doesn't specify valid lock
          information, or the file associated with FILEDES doesn't
          support locks.

    `ENOLCK'
          The system has run out of file lock resources; there are
          already too many file locks in place.

          Well-designed file systems never report this error, because
          they have no limitation on the number of locks.  However, you
          must still take account of the possibility of this error, as
          it could result from network access to a file system on
          another machine.

 - Macro: int F_SETLKW
     This macro is used as the COMMAND argument to `fcntl', to specify
     that it should set or clear a lock.  It is just like the `F_SETLK'
     command, but causes the process to block (or wait) until the
     request can be specified.

     This command requires a third argument of type `struct flock *', as
     for the `F_SETLK' command.

     The `fcntl' return values and errors are the same as for the
     `F_SETLK' command, but these additional `errno' error conditions
     are defined for this command:

    `EINTR'
          The function was interrupted by a signal while it was waiting.
          *Note Interrupted Primitives::.

    `EDEADLK'
          The specified region is being locked by another process.  But
          that process is waiting to lock a region which the current
          process has locked, so waiting for the lock would result in
          deadlock.  The system does not guarantee that it will detect
          all such conditions, but it lets you know if it notices one.

   The following macros are defined for use as values for the `l_type'
member of the `flock' structure.  The values are integer constants.

`F_RDLCK'
     This macro is used to specify a read (or shared) lock.

`F_WRLCK'
     This macro is used to specify a write (or exclusive) lock.

`F_UNLCK'
     This macro is used to specify that the region is unlocked.

   As an example of a situation where file locking is useful, consider a
program that can be run simultaneously by several different users, that
logs status information to a common file.  One example of such a program
might be a game that uses a file to keep track of high scores.  Another
example might be a program that records usage or accounting information
for billing purposes.

   Having multiple copies of the program simultaneously writing to the
file could cause the contents of the file to become mixed up.  But you
can prevent this kind of problem by setting a write lock on the file
before actually writing to the file.

   If the program also needs to read the file and wants to make sure
that the contents of the file are in a consistent state, then it can
also use a read lock.  While the read lock is set, no other process can
lock that part of the file for writing.

   Remember that file locks are only a *voluntary* protocol for
controlling access to a file.  There is still potential for access to
the file by programs that don't use the lock protocol.


File: libc.info,  Node: Interrupt Input,  Next: IOCTLs,  Prev: File Locks,  Up: Low-Level I/O

Interrupt-Driven Input
======================

   If you set the `O_ASYNC' status flag on a file descriptor (*note
File Status Flags::.), a `SIGIO' signal is sent whenever input or
output becomes possible on that file descriptor.  The process or
process group to receive the signal can be selected by using the
`F_SETOWN' command to the `fcntl' function.  If the file descriptor is
a socket, this also selects the recipient of `SIGURG' signals that are
delivered when out-of-band data arrives on that socket; see *Note
Out-of-Band Data::.  (`SIGURG' is sent in any situation where `select'
would report the socket as having an "exceptional condition".  *Note
Waiting for I/O::.)

   If the file descriptor corresponds to a terminal device, then `SIGIO'
signals are sent to the foreground process group of the terminal.
*Note Job Control::.

   The symbols in this section are defined in the header file `fcntl.h'.

 - Macro: int F_GETOWN
     This macro is used as the COMMAND argument to `fcntl', to specify
     that it should get information about the process or process group
     to which `SIGIO' signals are sent.  (For a terminal, this is
     actually the foreground process group ID, which you can get using
     `tcgetpgrp'; see *Note Terminal Access Functions::.)

     The return value is interpreted as a process ID; if negative, its
     absolute value is the process group ID.

     The following `errno' error condition is defined for this command:

    `EBADF'
          The FILEDES argument is invalid.

 - Macro: int F_SETOWN
     This macro is used as the COMMAND argument to `fcntl', to specify
     that it should set the process or process group to which `SIGIO'
     signals are sent.  This command requires a third argument of type
     `pid_t' to be passed to `fcntl', so that the form of the call is:

          fcntl (FILEDES, F_SETOWN, PID)

     The PID argument should be a process ID.  You can also pass a
     negative number whose absolute value is a process group ID.

     The return value from `fcntl' with this command is -1 in case of
     error and some other value if successful.  The following `errno'
     error conditions are defined for this command:

    `EBADF'
          The FILEDES argument is invalid.

    `ESRCH'
          There is no process or process group corresponding to PID.


File: libc.info,  Node: IOCTLs,  Prev: Interrupt Input,  Up: Low-Level I/O

Generic I/O Control operations
==============================

   The GNU system can handle most input/output operations on many
different devices and objects in terms of a few file primitives -
`read', `write' and `lseek'.  However, most devices also have a few
peculiar operations which do not fit into this model. Such as:

   * Changing the character font used on a terminal.

   * Telling a magnetic tape system to rewind or fast forward.  (Since
     they cannot move in byte increments, `lseek' is inapplicable).

   * Ejecting a disk from a drive.

   * Playing an audio track from a CD-ROM drive.

   * Maintaining routing tables for a network.

   Although some such objects such as sockets and terminals (1) have
special functions of their own, it would not be practical to create
functions for all these cases.

   Instead these minor operations, known as "IOCTL"s, are assigned code
numbers and multiplexed through the `ioctl' function, defined in
`sys/ioctl.h'.  The code numbers themselves are defined in many
different headers.

 - Function: int ioctl (int FILEDES, int COMMAND, ...)
     The `ioctl' function performs the generic I/O operation COMMAND on
     FILEDES.

     A third argument is usually present, either a single number or a
     pointer to a structure.  The meaning of this argument, the
     returned value, and any error codes depends upon the command used.
     Often -1 is returned for a failure.


   On some systems, IOCTLs used by different devices share the same
numbers.  Thus, although use of an inappropriate IOCTL *usually* only
produces an error, you should not attempt to use device-specific IOCTLs
on an unknown device.

   Most IOCTLs are OS-specific and/or only used in special system
utilities, and are thus beyond the scope of this document.  For an
example of the use of an IOCTL, see *Note Out-of-Band Data::.

   ---------- Footnotes ----------

   (1) Actually, the terminal-specific functions are implemented with
IOCTLs on many platforms.


File: libc.info,  Node: File System Interface,  Next: Pipes and FIFOs,  Prev: Low-Level I/O,  Up: Top

File System Interface
*********************

   This chapter describes the GNU C library's functions for manipulating
files.  Unlike the input and output functions (*note I/O on Streams::.;
*note Low-Level I/O::.), these functions are concerned with operating
on the files themselves, rather than on their contents.

   Among the facilities described in this chapter are functions for
examining or modifying directories, functions for renaming and deleting
files, and functions for examining and setting file attributes such as
access permissions and modification times.

* Menu:

* Working Directory::           This is used to resolve relative
				 file names.
* Accessing Directories::       Finding out what files a directory
				 contains.
* Working on Directory Trees::  Apply actions to all files or a selectable
                                 subset of a directory hierarchy.
* Hard Links::                  Adding alternate names to a file.
* Symbolic Links::              A file that "points to" a file name.
* Deleting Files::              How to delete a file, and what that means.
* Renaming Files::              Changing a file's name.
* Creating Directories::        A system call just for creating a directory.
* File Attributes::             Attributes of individual files.
* Making Special Files::        How to create special files.
* Temporary Files::             Naming and creating temporary files.


File: libc.info,  Node: Working Directory,  Next: Accessing Directories,  Up: File System Interface

Working Directory
=================

   Each process has associated with it a directory, called its "current
working directory" or simply "working directory", that is used in the
resolution of relative file names (*note File Name Resolution::.).

   When you log in and begin a new session, your working directory is
initially set to the home directory associated with your login account
in the system user database.  You can find any user's home directory
using the `getpwuid' or `getpwnam' functions; see *Note User Database::.

   Users can change the working directory using shell commands like
`cd'.  The functions described in this section are the primitives used
by those commands and by other programs for examining and changing the
working directory.

   Prototypes for these functions are declared in the header file
`unistd.h'.

 - Function: char * getcwd (char *BUFFER, size_t SIZE)
     The `getcwd' function returns an absolute file name representing
     the current working directory, storing it in the character array
     BUFFER that you provide.  The SIZE argument is how you tell the
     system the allocation size of BUFFER.

     The GNU library version of this function also permits you to
     specify a null pointer for the BUFFER argument.  Then `getcwd'
     allocates a buffer automatically, as with `malloc' (*note
     Unconstrained Allocation::.).  If the SIZE is greater than zero,
     then the buffer is that large; otherwise, the buffer is as large
     as necessary to hold the result.

     The return value is BUFFER on success and a null pointer on
     failure.  The following `errno' error conditions are defined for
     this function:

    `EINVAL'
          The SIZE argument is zero and BUFFER is not a null pointer.

    `ERANGE'
          The SIZE argument is less than the length of the working
          directory name.  You need to allocate a bigger array and try
          again.

    `EACCES'
          Permission to read or search a component of the file name was
          denied.

   You could implement the behavior of GNU's `getcwd (NULL, 0)' using
only the standard behavior of `getcwd':

     char *
     gnu_getcwd ()
     {
       int size = 100;
       char *buffer = (char *) xmalloc (size);
     
       while (1)
         {
           char *value = getcwd (buffer, size);
           if (value != 0)
             return buffer;
           size *= 2;
           free (buffer);
           buffer = (char *) xmalloc (size);
         }
     }

*Note Malloc Examples::, for information about `xmalloc', which is not
a library function but is a customary name used in most GNU software.

 - Function: char * getwd (char *BUFFER)
     This is similar to `getcwd', but has no way to specify the size of
     the buffer.  The GNU library provides `getwd' only for backwards
     compatibility with BSD.

     The BUFFER argument should be a pointer to an array at least
     `PATH_MAX' bytes long (*note Limits for Files::.).  In the GNU
     system there is no limit to the size of a file name, so this is not
     necessarily enough space to contain the directory name.  That is
     why this function is deprecated.

 - Function: int chdir (const char *FILENAME)
     This function is used to set the process's working directory to
     FILENAME.

     The normal, successful return value from `chdir' is `0'.  A value
     of `-1' is returned to indicate an error.  The `errno' error
     conditions defined for this function are the usual file name
     syntax errors (*note File Name Errors::.), plus `ENOTDIR' if the
     file FILENAME is not a directory.


File: libc.info,  Node: Accessing Directories,  Next: Working on Directory Trees,  Prev: Working Directory,  Up: File System Interface

Accessing Directories
=====================

   The facilities described in this section let you read the contents
of a directory file.  This is useful if you want your program to list
all the files in a directory, perhaps as part of a menu.

   The `opendir' function opens a "directory stream" whose elements are
directory entries.  You use the `readdir' function on the directory
stream to retrieve these entries, represented as `struct dirent'
objects.  The name of the file for each entry is stored in the `d_name'
member of this structure.  There are obvious parallels here to the
stream facilities for ordinary files, described in *Note I/O on
Streams::.

* Menu:

* Directory Entries::           Format of one directory entry.
* Opening a Directory::         How to open a directory stream.
* Reading/Closing Directory::   How to read directory entries from the stream.
* Simple Directory Lister::     A very simple directory listing program.
* Random Access Directory::     Rereading part of the directory
                                 already read with the same stream.
* Scanning Directory Content::  Get entries for user selected subset of
                                 contents in given directory.
* Simple Directory Lister Mark II::  Revised version of the program.


File: libc.info,  Node: Directory Entries,  Next: Opening a Directory,  Up: Accessing Directories

Format of a Directory Entry
---------------------------

   This section describes what you find in a single directory entry, as
you might obtain it from a directory stream.  All the symbols are
declared in the header file `dirent.h'.

 - Data Type: struct dirent
     This is a structure type used to return information about directory
     entries.  It contains the following fields:

    `char d_name[]'
          This is the null-terminated file name component.  This is the
          only field you can count on in all POSIX systems.

    `ino_t d_fileno'
          This is the file serial number.  For BSD compatibility, you
          can also refer to this member as `d_ino'.  In the GNU system
          and most POSIX systems, for most files this the same as the
          `st_ino' member that `stat' will return for the file.  *Note
          File Attributes::.

    `unsigned char d_namlen'
          This is the length of the file name, not including the
          terminating null character.  Its type is `unsigned char'
          because that is the integer type of the appropriate size

    `unsigned char d_type'
          This is the type of the file, possibly unknown.  The
          following constants are defined for its value:

         `DT_UNKNOWN'
               The type is unknown.  On some systems this is the only
               value returned.

         `DT_REG'
               A regular file.

         `DT_DIR'
               A directory.

         `DT_FIFO'
               A named pipe, or FIFO.  *Note FIFO Special Files::.

         `DT_SOCK'
               A local-domain socket.

         `DT_CHR'
               A character device.

         `DT_BLK'
               A block device.

          This member is a BSD extension.  On systems where it is used,
          it corresponds to the file type bits in the `st_mode' member
          of `struct statbuf'.  On other systems it will always be
          DT_UNKNOWN.  These two macros convert between `d_type' values
          and `st_mode' values:

           - Function: int IFTODT (mode_t MODE)
               This returns the `d_type' value corresponding to MODE.

           - Function: mode_t DTTOIF (int DTYPE)
               This returns the `st_mode' value corresponding to DTYPE.

     This structure may contain additional members in the future.

     When a file has multiple names, each name has its own directory
     entry.  The only way you can tell that the directory entries
     belong to a single file is that they have the same value for the
     `d_fileno' field.

     File attributes such as size, modification times, and the like are
     part of the file itself, not any particular directory entry.
     *Note File Attributes::.


File: libc.info,  Node: Opening a Directory,  Next: Reading/Closing Directory,  Prev: Directory Entries,  Up: Accessing Directories

Opening a Directory Stream
--------------------------

   This section describes how to open a directory stream.  All the
symbols are declared in the header file `dirent.h'.

 - Data Type: DIR
     The `DIR' data type represents a directory stream.

   You shouldn't ever allocate objects of the `struct dirent' or `DIR'
data types, since the directory access functions do that for you.
Instead, you refer to these objects using the pointers returned by the
following functions.

 - Function: DIR * opendir (const char *DIRNAME)
     The `opendir' function opens and returns a directory stream for
     reading the directory whose file name is DIRNAME.  The stream has
     type `DIR *'.

     If unsuccessful, `opendir' returns a null pointer.  In addition to
     the usual file name errors (*note File Name Errors::.), the
     following `errno' error conditions are defined for this function:

    `EACCES'
          Read permission is denied for the directory named by
          `dirname'.

    `EMFILE'
          The process has too many files open.

    `ENFILE'
          The entire system, or perhaps the file system which contains
          the directory, cannot support any additional open files at
          the moment.  (This problem cannot happen on the GNU system.)

     The `DIR' type is typically implemented using a file descriptor,
     and the `opendir' function in terms of the `open' function.  *Note
     Low-Level I/O::.  Directory streams and the underlying file
     descriptors are closed on `exec' (*note Executing a File::.).


File: libc.info,  Node: Reading/Closing Directory,  Next: Simple Directory Lister,  Prev: Opening a Directory,  Up: Accessing Directories

Reading and Closing a Directory Stream
--------------------------------------

   This section describes how to read directory entries from a directory
stream, and how to close the stream when you are done with it.  All the
symbols are declared in the header file `dirent.h'.

 - Function: struct dirent * readdir (DIR *DIRSTREAM)
     This function reads the next entry from the directory.  It normally
     returns a pointer to a structure containing information about the
     file.  This structure is statically allocated and can be rewritten
     by a subsequent call.

     *Portability Note:* On some systems, `readdir' may not return
     entries for `.' and `..', even though these are always valid file
     names in any directory.  *Note File Name Resolution::.

     If there are no more entries in the directory or an error is
     detected, `readdir' returns a null pointer.  The following `errno'
     error conditions are defined for this function:

    `EBADF'
          The DIRSTREAM argument is not valid.

     `readdir' is not thread safe.  Multiple threads using `readdir' on
     the same DIRSTREAM may overwrite the return value.  Use
     `readdir_r' when this is critical.

 - Function: int readdir_r (DIR *DIRSTREAM, struct dirent *ENTRY,
          struct dirent **RESULT)
     This function is the reentrant version of `readdir'.  Like
     `readdir' it returns the next entry from the directory.  But to
     prevent conflicts for simultaneously running threads the result is
     not stored in some internal memory.  Instead the argument ENTRY
     has to point to a place where the result is stored.

     The return value is `0' in case the next entry was read
     successfully.  In this case a pointer to the result is returned in
     *RESULT.  It is not required that *RESULT is the same as ENTRY.
     If something goes wrong while executing `readdir_r' the function
     returns a value indicating the error (as described for `readdir').

     If there are no more directory entries, `readdir_r''s return value
     is `0', and *RESULT is set to `NULL'.

     *Portability Note:* On some systems, `readdir_r' may not return a
     terminated string as the file name even if no `d_reclen' element
     is available in `struct dirent' and the file name as the maximal
     allowed size.  Modern systems all have the `d_reclen' field and on
     old systems multi threading is not critical.  In any case, there
     is no such problem with the `readdir' function so that even on
     systems without `d_reclen' field one could use multiple threads by
     using external locking.

 - Function: int closedir (DIR *DIRSTREAM)
     This function closes the directory stream DIRSTREAM.  It returns
     `0' on success and `-1' on failure.

     The following `errno' error conditions are defined for this
     function:

    `EBADF'
          The DIRSTREAM argument is not valid.


File: libc.info,  Node: Simple Directory Lister,  Next: Random Access Directory,  Prev: Reading/Closing Directory,  Up: Accessing Directories

Simple Program to List a Directory
----------------------------------

   Here's a simple program that prints the names of the files in the
current working directory:

     #include <stddef.h>
     #include <stdio.h>
     #include <sys/types.h>
     #include <dirent.h>
     
     int
     main (void)
     {
       DIR *dp;
       struct dirent *ep;
     
       dp = opendir ("./");
       if (dp != NULL)
         {
           while (ep = readdir (dp))
             puts (ep->d_name);
           (void) closedir (dp);
         }
       else
         puts ("Couldn't open the directory.");
     
       return 0;
     }

   The order in which files appear in a directory tends to be fairly
random.  A more useful program would sort the entries (perhaps by
alphabetizing them) before printing them; see *Note Scanning Directory
Content::, and *Note Array Sort Function::.


File: libc.info,  Node: Random Access Directory,  Next: Scanning Directory Content,  Prev: Simple Directory Lister,  Up: Accessing Directories

Random Access in a Directory Stream
-----------------------------------

   This section describes how to reread parts of a directory that you
have already read from an open directory stream.  All the symbols are
declared in the header file `dirent.h'.

 - Function: void rewinddir (DIR *DIRSTREAM)
     The `rewinddir' function is used to reinitialize the directory
     stream DIRSTREAM, so that if you call `readdir' it returns
     information about the first entry in the directory again.  This
     function also notices if files have been added or removed to the
     directory since it was opened with `opendir'.  (Entries for these
     files might or might not be returned by `readdir' if they were
     added or removed since you last called `opendir' or `rewinddir'.)

 - Function: off_t telldir (DIR *DIRSTREAM)
     The `telldir' function returns the file position of the directory
     stream DIRSTREAM.  You can use this value with `seekdir' to
     restore the directory stream to that position.

 - Function: void seekdir (DIR *DIRSTREAM, off_t POS)
     The `seekdir' function sets the file position of the directory
     stream DIRSTREAM to POS.  The value POS must be the result of a
     previous call to `telldir' on this particular stream; closing and
     reopening the directory can invalidate values returned by
     `telldir'.


File: libc.info,  Node: Scanning Directory Content,  Next: Simple Directory Lister Mark II,  Prev: Random Access Directory,  Up: Accessing Directories

Scanning the Content of a Directory
-----------------------------------

   A higher-level interface to the directory handling functions is the
`scandir' function.  With its help one can select a subset of the
entries in a directory, possibly sort them and get as the result a list
of names.

 - Function: int scandir (const char *DIR, struct dirent ***NAMELIST,
          int (*SELECTOR) (const struct dirent *), int (*CMP) (const
          void *, const void *))
     The `scandir' function scans the contents of the directory selected
     by DIR.  The result in NAMELIST is an array of pointers to
     structure of type `struct dirent' which describe all selected
     directory entries and which is allocated using `malloc'.  Instead
     of always getting all directory entries returned, the user supplied
     function SELECTOR can be used to decide which entries are in the
     result.  Only the entries for which SELECTOR returns a nonzero
     value are selected.

     Finally the entries in the NAMELIST are sorted using the user
     supplied function CMP.  The arguments of the CMP function are of
     type `struct dirent **'.  I.e., one cannot directly use the
     `strcmp' or `strcoll' function; see the functions `alphasort' and
     `versionsort' below.

     The return value of the function gives the number of entries
     placed in NAMELIST.  If it is `-1' an error occurred (either the
     directory could not be opened for reading or the malloc call
     failed) and the global variable `errno' contains more information
     on the error.

   As said above the fourth argument to the `scandir' function must be
a pointer to a sorting function.  For the convenience of the programmer
the GNU C library contains implementations of functions which are very
helpful for this purpose.

 - Function: int alphasort (const void *A, const void *B)
     The `alphasort' function behaves like the `strcoll' function
     (*note String/Array Comparison::.).  The difference is that the
     arguments are not string pointers but instead they are of type
     `struct dirent **'.

     Return value of `alphasort' is less than, equal to, or greater than
     zero depending on the order of the two entries A and B.

 - Function: int versionsort (const void *A, const void *B)
     The `versionsort' function is like `alphasort', excepted that it
     uses the `strverscmp' function internally.

   If the filesystem supports large files we cannot use the `scandir'
anymore since the `dirent' structure might not able to contain all the
information.  The LFS provides the new type `struct dirent64'.  To use
this we need a new function.

 - Function: int scandir64 (const char *DIR, struct dirent64
          ***NAMELIST, int (*SELECTOR) (const struct dirent64 *), int
          (*CMP) (const void *, const void *))
     The `scandir64' function works like the `scandir' function only
     that the directory entries it returns are described by elements of
     type `struct dirent64'.  The function pointed to by SELECTOR is
     again used to select the wanted entries only that SELECTOR now
     must point to a function which takes a `struct dirent64 *'
     parameter.

     The CMP now must be a function which expects its two arguments to
     be of type `struct dirent64 **'.

   As just said the function expected as the fourth is different from
the function expected in `scandir'.  Therefore we cannot use the
`alphasort' and `versionsort' functions anymore.  Instead we have two
similar functions available.

 - Function: int alphasort64 (const void *A, const void *B)
     The `alphasort64' function behaves like the `strcoll' function
     (*note String/Array Comparison::.).  The difference is that the
     arguments are not string pointers but instead they are of type
     `struct dirent64 **'.

     Return value of `alphasort64' is less than, equal to, or greater
     than zero depending on the order of the two entries A and B.

 - Function: int versionsort64 (const void *A, const void *B)
     The `versionsort64' function is like `alphasort64', excepted that
     it uses the `strverscmp' function internally.

   It is important not to mix the use of `scandir' and the 64 bits
comparison functions or vice versa.  There are systems on which this
works but on others it will fail miserably.


File: libc.info,  Node: Simple Directory Lister Mark II,  Prev: Scanning Directory Content,  Up: Accessing Directories

Simple Program to List a Directory, Mark II
-------------------------------------------

   Here is a revised version of the directory lister found above (*note
Simple Directory Lister::.).  Using the `scandir' function we can avoid
using the functions which directly work with the directory contents.
After the call the found entries are available for direct used.

     #include <stdio.h>
     #include <dirent.h>
     
     static int
     one (struct dirent *unused)
     {
       return 1;
     }
     
     int
     main (void)
     {
       struct dirent **eps;
       int n;
     
       n = scandir ("./", &eps, one, alphasort);
       if (n >= 0)
         {
           int cnt;
           for (cnt = 0; cnt < n; ++cnt)
             puts (eps[cnt]->d_name);
         }
       else
         perror ("Couldn't open the directory");
     
       return 0;
     }

   Please note the simple selector function for this example.  Since we
want to see all directory entries we always return `1'.

