Dies ist die Info-Datei libc.info, hergestellt von Makeinfo Version
1.68 aus der Eingabe-Datei 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.07 DRAFT, last updated 4 Oct 1996, of `The GNU C
Library Reference Manual', for Version 2.00 Beta.

   Copyright (C) 1993, '94, '95, '96, '97 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: 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,  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: 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 described in *Note I/O on
Streams:: and *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.

* Menü:

* Working Directory::           This is used to resolve relative
				 file names.
* Accessing Directories::       Finding out what files a directory
				 contains.
* 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'.

 - Fonction: 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.

   Here is an example showing how 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.

 - Fonction: 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.

 - Fonction: 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: Hard Links,  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::.

* Menü:

* 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.  Each value except DT_UNKNOWN
          corresponds to the file type bits in the `st_mode' member of
          `struct statbuf'.  These two macros convert between `d_type'
          values and `st_mode' values:

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

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

     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.

 - Fonction: 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'.

 - Fonction: 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.

 - Fonction: 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 `-1'.  The `errno' variable is set like 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.

 - Fonction: 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'.

 - Fonction: 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'.)

 - Fonction: 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.

 - Fonction: 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.

 - Fonction: int scandir (const char *DIR, struct dirent ***NAMELIST,
          int (*SELECTOR) (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 function `alphasort' below.

     The return value of the function gives the number of entries
     placed in NAMELIST.  If it is `-1' an error occurred 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 an implementation of a function which is very
helpful for this purpose.

 - Fonction: int alphasort (const void *A, const void *B)
     The `alphasort' function behaves like the `strcmp' 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 is less than, equal to, or greater than zero
     depending on the order of the two entries A and B.


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'.


File: libc.info,  Node: Hard Links,  Next: Symbolic Links,  Prev: Accessing Directories,  Up: File System Interface

Hard Links
==========

   In POSIX systems, one file can have many names at the same time.
All of the names are equally real, and no one of them is preferred to
the others.

   To add a name to a file, use the `link' function.  (The new name is
also called a "hard link" to the file.)  Creating a new link to a file
does not copy the contents of the file; it simply makes a new name by
which the file can be known, in addition to the file's existing name or
names.

   One file can have names in several directories, so the the
organization of the file system is not a strict hierarchy or tree.

   In most implementations, it is not possible to have hard links to the
same file in multiple file systems.  `link' reports an error if you try
to make a hard link to the file from another file system when this
cannot be done.

   The prototype for the `link' function is declared in the header file
`unistd.h'.

 - Fonction: int link (const char *OLDNAME, const char *NEWNAME)
     The `link' function makes a new link to the existing file named by
     OLDNAME, under the new name NEWNAME.

     This function returns a value of `0' if it is successful and `-1'
     on failure.  In addition to the usual file name errors (*note File
     Name Errors::.) for both OLDNAME and NEWNAME, the following
     `errno' error conditions are defined for this function:

    `EACCES'
          You are not allowed to write the directory in which the new
          link is to be written.

    `EEXIST'
          There is already a file named NEWNAME.  If you want to replace
          this link with a new link, you must remove the old link
          explicitly first.

    `EMLINK'
          There are already too many links to the file named by OLDNAME.
          (The maximum number of links to a file is `LINK_MAX'; see
          *Note Limits for Files::.)

    `ENOENT'
          The file named by OLDNAME doesn't exist.  You can't make a
          link to a file that doesn't exist.

    `ENOSPC'
          The directory or file system that would contain the new link
          is full and cannot be extended.

    `EPERM'
          In the GNU system and some others, you cannot make links to
          directories.  Many systems allow only privileged users to do
          so.  This error is used to report the problem.

    `EROFS'
          The directory containing the new link can't be modified
          because it's on a read-only file system.

    `EXDEV'
          The directory specified in NEWNAME is on a different file
          system than the existing file.

    `EIO'
          A hardware error occurred while trying to read or write the
          to filesystem.


File: libc.info,  Node: Symbolic Links,  Next: Deleting Files,  Prev: Hard Links,  Up: File System Interface

Symbolic Links
==============

   The GNU system supports "soft links" or "symbolic links".  This is a
kind of "file" that is essentially a pointer to another file name.
Unlike hard links, symbolic links can be made to directories or across
file systems with no restrictions.  You can also make a symbolic link
to a name which is not the name of any file.  (Opening this link will
fail until a file by that name is created.)  Likewise, if the symbolic
link points to an existing file which is later deleted, the symbolic
link continues to point to the same file name even though the name no
longer names any file.

   The reason symbolic links work the way they do is that special things
happen when you try to open the link.  The `open' function realizes you
have specified the name of a link, reads the file name contained in the
link, and opens that file name instead.  The `stat' function likewise
operates on the file that the symbolic link points to, instead of on
the link itself.

   By contrast, other operations such as deleting or renaming the file
operate on the link itself.  The functions `readlink' and `lstat' also
refrain from following symbolic links, because their purpose is to
obtain information about the link.  So does `link', the function that
makes a hard link--it makes a hard link to the symbolic link, which one
rarely wants.

   Prototypes for the functions listed in this section are in
`unistd.h'.

 - Fonction: int symlink (const char *OLDNAME, const char *NEWNAME)
     The `symlink' function makes a symbolic link to OLDNAME named
     NEWNAME.

     The normal return value from `symlink' is `0'.  A return value of
     `-1' indicates an error.  In addition to the usual file name
     syntax errors (*note File Name Errors::.), the following `errno'
     error conditions are defined for this function:

    `EEXIST'
          There is already an existing file named NEWNAME.

    `EROFS'
          The file NEWNAME would exist on a read-only file system.

    `ENOSPC'
          The directory or file system cannot be extended to make the
          new link.

    `EIO'
          A hardware error occurred while reading or writing data on
          the disk.


 - Fonction: int readlink (const char *FILENAME, char *BUFFER, size_t
          SIZE)
     The `readlink' function gets the value of the symbolic link
     FILENAME.  The file name that the link points to is copied into
     BUFFER.  This file name string is *not* null-terminated;
     `readlink' normally returns the number of characters copied.  The
     SIZE argument specifies the maximum number of characters to copy,
     usually the allocation size of BUFFER.

     If the return value equals SIZE, you cannot tell whether or not
     there was room to return the entire name.  So make a bigger buffer
     and call `readlink' again.  Here is an example:

          char *
          readlink_malloc (char *filename)
          {
            int size = 100;
          
            while (1)
              {
                char *buffer = (char *) xmalloc (size);
                int nchars = readlink (filename, buffer, size);
                if (nchars < size)
                  return buffer;
                free (buffer);
                size *= 2;
              }
          }

     A value of `-1' is returned in case of error.  In addition to the
     usual file name errors (*note File Name Errors::.), the following
     `errno' error conditions are defined for this function:

    `EINVAL'
          The named file is not a symbolic link.

    `EIO'
          A hardware error occurred while reading or writing data on
          the disk.


File: libc.info,  Node: Deleting Files,  Next: Renaming Files,  Prev: Symbolic Links,  Up: File System Interface

Deleting Files
==============

   You can delete a file with the functions `unlink' or `remove'.

   Deletion actually deletes a file name.  If this is the file's only
name, then the file is deleted as well.  If the file has other names as
well (*note Hard Links::.), it remains accessible under its other names.

 - Fonction: int unlink (const char *FILENAME)
     The `unlink' function deletes the file name FILENAME.  If this is
     a file's sole name, the file itself is also deleted.  (Actually,
     if any process has the file open when this happens, deletion is
     postponed until all processes have closed the file.)

     The function `unlink' is declared in the header file `unistd.h'.

     This function returns `0' on successful completion, and `-1' on
     error.  In addition to the usual file name errors (*note File Name
     Errors::.), the following `errno' error conditions are defined for
     this function:

    `EACCES'
          Write permission is denied for the directory from which the
          file is to be removed, or the directory has the sticky bit
          set and you do not own the file.

    `EBUSY'
          This error indicates that the file is being used by the
          system in such a way that it can't be unlinked.  For example,
          you might see this error if the file name specifies the root
          directory or a mount point for a file system.

    `ENOENT'
          The file name to be deleted doesn't exist.

    `EPERM'
          On some systems, `unlink' cannot be used to delete the name
          of a directory, or can only be used this way by a privileged
          user.  To avoid such problems, use `rmdir' to delete
          directories.  (In the GNU system `unlink' can never delete
          the name of a directory.)

    `EROFS'
          The directory in which the file name is to be deleted is on a
          read-only file system, and can't be modified.

 - Fonction: int rmdir (const char *FILENAME)
     The `rmdir' function deletes a directory.  The directory must be
     empty before it can be removed; in other words, it can only contain
     entries for `.' and `..'.

     In most other respects, `rmdir' behaves like `unlink'.  There are
     two additional `errno' error conditions defined for `rmdir':

    `ENOTEMPTY'
    `EEXIST'
          The directory to be deleted is not empty.

     These two error codes are synonymous; some systems use one, and
     some use the other.  The GNU system always uses `ENOTEMPTY'.

     The prototype for this function is declared in the header file
     `unistd.h'.

 - Fonction: int remove (const char *FILENAME)
     This is the ISO C function to remove a file.  It works like
     `unlink' for files and like `rmdir' for directories.  `remove' is
     declared in `stdio.h'.


File: libc.info,  Node: Renaming Files,  Next: Creating Directories,  Prev: Deleting Files,  Up: File System Interface

Renaming Files
==============

   The `rename' function is used to change a file's name.

 - Fonction: int rename (const char *OLDNAME, const char *NEWNAME)
     The `rename' function renames the file name OLDNAME with NEWNAME.
     The file formerly accessible under the name OLDNAME is afterward
     accessible as NEWNAME instead.  (If the file had any other names
     aside from OLDNAME, it continues to have those names.)

     The directory containing the name NEWNAME must be on the same file
     system as the file (as indicated by the name OLDNAME).

     One special case for `rename' is when OLDNAME and NEWNAME are two
     names for the same file.  The consistent way to handle this case
     is to delete OLDNAME.  However, POSIX requires that in this case
     `rename' do nothing and report success--which is inconsistent.  We
     don't know what your operating system will do.

     If the OLDNAME is not a directory, then any existing file named
     NEWNAME is removed during the renaming operation.  However, if
     NEWNAME is the name of a directory, `rename' fails in this case.

     If the OLDNAME is a directory, then either NEWNAME must not exist
     or it must name a directory that is empty.  In the latter case,
     the existing directory named NEWNAME is deleted first.  The name
     NEWNAME must not specify a subdirectory of the directory `oldname'
     which is being renamed.

     One useful feature of `rename' is that the meaning of the name
     NEWNAME changes "atomically" from any previously existing file by
     that name to its new meaning (the file that was called OLDNAME).
     There is no instant at which NEWNAME is nonexistent "in between"
     the old meaning and the new meaning.  If there is a system crash
     during the operation, it is possible for both names to still
     exist; but NEWNAME will always be intact if it exists at all.

     If `rename' fails, it returns `-1'.  In addition to the usual file
     name errors (*note File Name Errors::.), the following `errno'
     error conditions are defined for this function:

    `EACCES'
          One of the directories containing NEWNAME or OLDNAME refuses
          write permission; or NEWNAME and OLDNAME are directories and
          write permission is refused for one of them.

    `EBUSY'
          A directory named by OLDNAME or NEWNAME is being used by the
          system in a way that prevents the renaming from working.
          This includes directories that are mount points for
          filesystems, and directories that are the current working
          directories of processes.

    `ENOTEMPTY'
    `EEXIST'
          The directory NEWNAME isn't empty.  The GNU system always
          returns `ENOTEMPTY' for this, but some other systems return
          `EEXIST'.

    `EINVAL'
          The OLDNAME is a directory that contains NEWNAME.

    `EISDIR'
          The NEWNAME names a directory, but the OLDNAME doesn't.

    `EMLINK'
          The parent directory of NEWNAME would have too many links.

    `ENOENT'
          The file named by OLDNAME doesn't exist.

    `ENOSPC'
          The directory that would contain NEWNAME has no room for
          another entry, and there is no space left in the file system
          to expand it.

    `EROFS'
          The operation would involve writing to a directory on a
          read-only file system.

    `EXDEV'
          The two file names NEWNAME and OLDNAMES are on different file
          systems.

