stat(), stat64()

Get information about a file or directory, given a path

Synopsis:

#include <sys/stat.h>

int stat( const char * path, 
          struct stat * buf );

int stat64( const char * path, 
            struct stat64 * buf );

Arguments:

path
The path of the file or directory that you want information about.
buf
A pointer to a buffer where the function can store the information; see below.

Library:

libc

Use the -l c option to qcc to link against this library. This library is usually included automatically.

Description:

The stat() and stat64() functions obtain information about the file or directory referenced in path. This information is placed in the structure located at the address indicated by buf. The stat64() function is a large-file support version of stat().

stat structure

Here's the stat structure that's defined in <sys/stat.h>:

struct stat {
#if _FILE_OFFSET_BITS - 0 == 64
    ino_t           st_ino;         /* File serial number. */
    off_t           st_size;        /* File size in bytes.  */
#elif !defined(_FILE_OFFSET_BITS) || _FILE_OFFSET_BITS == 32
#if defined(__LITTLEENDIAN__)
    ino_t           st_ino;         /* File serial number. */
    ino_t           st_ino_hi;
    off_t           st_size;
    off_t           st_size_hi;
#elif defined(__BIGENDIAN__)
    ino_t           st_ino_hi;
    ino_t           st_ino;         /* File serial number. */
    off_t           st_size_hi;
    off_t           st_size;
#else
 #error endian not configured for system
#endif
#else
 #error _FILE_OFFSET_BITS value is unsupported
#endif
    dev_t           st_dev;         /* ID of the device containing the file. */
    dev_t           st_rdev;        /* Device ID.                            */
    uid_t           st_uid;         /* User ID of file.                      */
    gid_t           st_gid;         /* Group ID of file.                     */
    time_t          st_mtime;       /* Time of last data modification.       */
    time_t          st_atime;       /* Time when file data was last accessed.*/
    time_t          st_ctime;       /* Time of last file status change.      */
    mode_t          st_mode;        /* File types and permissions.           */
    nlink_t         st_nlink;       /* Number of hard links to the file.     */
    blksize_t       st_blocksize;   /* Size of a block used by st_nblocks.   */
    int32_t         st_nblocks;     /* Number of blocks st_blocksize blocks. */
    blksize_t       st_blksize;     /* Preferred I/O block size for object.   */
#if _FILE_OFFSET_BITS - 0 == 64
    blkcnt_t        st_blocks;      /* No. of 512-byte blocks allocated for a file. */
#elif !defined(_FILE_OFFSET_BITS) || _FILE_OFFSET_BITS == 32
#if defined(__LITTLEENDIAN__)
    blkcnt_t        st_blocks;      /* No. of 512-byte blocks allocated for a file. */
    blkcnt_t        st_blocks_hi;
#elif defined(__BIGENDIAN__)
    blkcnt_t        st_blocks_hi;
    blkcnt_t        st_blocks;
#else
 #error endian not configured for system
#endif
#else
 #error _FILE_OFFSET_BITS value is unsupported
#endif
};

st_mode bits

The bits in the st_mode member identify the following:

Three-digit octal modes include the access permissions; some utilities, such as find, use six-digit octal modes that include the rest:

Name Octal value Meaning
S_IFBLK 060000 Block special file
S_IFCHR 020000 Character special file
S_IFDIR 040000 Directory
S_IFIFO 010000 FIFO special file
S_IFLNK 120000 Symbolic link
S_IFNAM 050000 Special named file
S_IFREG 100000 Regular file
S_IFSOCK 140000 Socket
S_ISUID 004000 Set user ID on execution. The process's effective user ID is set to the file's owner when the file is run as a program. On a regular file, this bit should be cleared on any write.
S_ISGID 002000 Set group ID on execution. The process's effective group ID is set to the file's group when the file is run as a program. On a regular file, this bit should be cleared on any write.
S_ISVTX 001000 Sticky bit
S_IRUSR 000400 Owner has read permission
S_IWUSR 000200 Owner has write permission
S_IXUSR 000100 Owner has execute/search permission
S_IRWXU 000700 Owner has read, write, and execute/search permissions; a bitwise inclusive OR of S_IRUSR, S_IWUSR and S_IXUSR
S_IRGRP 000040 Group has read permission
S_IWGRP 000020 Group has write permission
S_IXGRP 000010 Group has execute/search permission
S_IRWXG 000070 Group has read, write, and execute/search permissions; a bitwise inclusive OR of S_IRGRP, S_IWGRP and S_IXGRP
S_IROTH 000004 Others have read permission
S_IWOTH 000002 Others have write permission
S_IXOTH 000001 Others have execute/search permission
S_IRWXO 000007 Others have read, write, and execute/search permissions; a bitwise inclusive OR of S_IROTH, S_IWOTH and S_IXOTH

S_IFMT is a mask that isolates the file-type bits. For information about macros that you can use to check the file type, see Macros,” below.

The following bits define miscellaneous permissions used by other implementations:

Bit Equivalent
S_IEXEC S_IXUSR
S_IREAD S_IRUSR
S_IWRITE S_IWUSR

Macros

The following macros test whether a file is of a specified type. The value m supplied to the macros is the value of the st_mode field of a stat structure. The macros evaluate to a nonzero value if the test is true, and zero if the test is false.

S_ISBLK(m)
Test for block special file.
S_ISCHR(m)
Test for character special file.
S_ISDIR(m)
Test for directory file.
S_ISFIFO(m)
Test for FIFO.
S_ISLNK(m)
Test for symbolic link.
S_ISNAM(m)
Test for special named file.
S_ISREG(m)
Test for regular file.
S_ISSOCK(m)
Test for socket.

These macros test whether a file is of the specified type. The value of the buf argument supplied to the macros is a pointer to a stat structure. The macro evaluates to a nonzero value if the specified object is implemented as a distinct file type and the specified file type is contained in the stat structure referenced by the pointer buf. Otherwise, the macro evaluates to zero.

S_TYPEISMQ(buf)
Test for message queue.
S_TYPEISSEM(buf)
Test for semaphore.
S_TYPEISSHM(buf)
Test for shared memory object.

These macros manipulate device IDs:

major( device )
Extract the major number from a device ID.
minor( device )
Extract the minor number from a device ID.
makedev( node, major, minor)
Build a device ID from the given numbers. Currently, the node argument isn't used and must be zero.

The st_rdev member of the stat structure is a device ID that consists of:

Returns:

0
Success.
-1
An error occurred (errno is set).

Errors:

EACCES
Search permission is denied for a component of path.
EINTR
The function was interrupted by a signal.
EIO
A physical error occurred on the block device.
ELOOP
Too many levels of symbolic links or prefixes.
ENAMETOOLONG
The argument path exceeds PATH_MAX in length, or a pathname component is longer than NAME_MAX. These manifests are defined in the <limits.h> header file.
ENOENT
The named file doesn't exist, or path is an empty string.
ENOSYS
The stat() function isn't implemented for the filesystem specified in path.
ENOTDIR
A component of path isn't a directory.
EOVERFLOW
The file size in bytes or the number of blocks allocated to the file or the file serial number can't be represented correctly in the structure pointed to by buf.

Examples:

Determine the size of a file:

#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>

int main( void )
  {
    struct stat buf;

    if( stat( "file", &buf ) != -1 ) {
      printf( "File size = %d\n", buf.st_size );
    }
    return EXIT_SUCCESS;
  }

Determine the amount of free memory:

#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>

int main () {
   struct stat buf;
   
   if ( stat( "/proc", &buf ) == -1) {
      perror ("stat" );
      return EXIT_FAILURE;
   } else {
      printf ("Free memory: %d bytes\n", buf.st_size);
      return EXIT_SUCCESS;
   }
}

Classification:

stat() is POSIX 1003.1; stat64() is Large-file support

Safety:
Cancellation point No
Interrupt handler No
Signal handler Yes
Thread Yes

See also:

errno, fstat(), fstat64(), lstat()