Go to main content

man pages section 2: System Calls

Exit Print View

Updated: Wednesday, July 27, 2022
 
 

stat (2)

Name

stat, lstat, fstat, fstatat - get file status

Synopsis

#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>

int stat(const char *restrict
 path, struct stat *restrict buf);
int lstat(const char *restrict path, struct stat *restrict buf);
int fstat(int fildes, struct stat *buf);
int fstatat(int fildes, const char *path, struct stat *buf,
     int flag);

Description

The stat() function obtains information about the file pointed to by path. Read, write, or execute permission of the named file is not required, but all directories listed in the path name leading to the file must be searchable.

The lstat() function obtains file attributes similar to stat(), except when the named file is a symbolic link; in that case lstat() returns information about the link, while stat() returns information about the file the link references.

The fstat() function obtains information about an open file known by the file descriptor fildes, obtained from a successful call to a function such as open(2), creat(2), dup(2), fcntl(2), or pipe(2). If fildes references a shared memory object, the system updates in the stat structure pointed to by the buf argument only the st_uid, st_gid, st_size, and st_mode fields, and only the S_IRUSR, S_IWUSR, S_IRGRP, S_IWGRP, S_IROTH, and S_IWOTH file permission bits need be valid. The system can update other fields and flags. The fstat() function updates any pending time-related fields before writing to the stat structure.

The fstatat() function obtains file attributes similar to the stat(), lstat(), and fstat() functions. If the path argument is a relative path, it is resolved relative to the fildes argument rather than the current working directory. If path is absolute, the fildes argument is unused. If the fildes argument has the special value AT_FDCWD, relative paths are resolved from the current working directory. If AT_SYMLINK_NOFOLLOW is set in the flag argument, the function behaves like lstat() and does not automatically follow symbolic links. See fsattr(7). If _AT_TRIGGER is set in the flag argument and the vnode is an autofs trigger mount point, the mount is performed and the function returns the attributes of the root of the mounted filesystem.

The buf argument is a pointer to a stat structure into which information is placed concerning the file. A stat structure includes the following members:

mode_t         st_mode;      /* File mode (see mknod(2)) */
ino_t          st_ino;       /* File serial number */
dev_t          st_dev;       /* ID of device containing */
                             /* a directory entry for this file */
dev_t          st_rdev;      /* ID of device */
                             /* This entry is defined only for */
                             /* char special or block special files */
nlink_t        st_nlink;     /* Number of links */
uid_t          st_uid;       /* User ID of the file's owner */
gid_t          st_gid;       /* Group ID of the file's group */
off_t          st_size;      /* File size in bytes */
timespec_t     st_atim;      /* Timestamp of last access */
timespec_t     st_mtim;      /* Timestamp of last data modification */
timespec_t     st_ctim;      /* Timestamp of last file status change */
                     /* Timestamps contain seconds and nanoseconds */
                     /* since 00:00:00 UTC, Jan. 1, 1970 */
long           st_blksize;   /* Preferred I/O block size */
blkcnt_t       st_blocks;    /* Number of 512 byte blocks allocated*/
char           st_fstype[_ST_FSTYPSZ];
                             /* Null-terminated type of filesystem */

Descriptions of structure members are as follows:

st_mode

The mode of the file as described for the mknod() function. In addition to the modes described on the mknod(2) manual page, the mode of a file can also be S_IFSOCK if the file is a socket, S_IFDOOR if the file is a door, S_IFPORT if the file is an event port, or S_IFLNK if the file is a symbolic link. S_IFLNK can be returned either by lstat() or by fstatat() when the AT_SYMLINK_NOFOLLOW flag is set.

To check the type of a file, compare st_mode & S_IFMT against the appropriate S_IF* macro value, or use the S_IS* convenience macros defined in stat.h(3HEAD). To check the access mode of a file, compare st_mode & S_IAMB against the appropriate file permission bitmask macros defined in stat.h(3HEAD).

st_ino

This field uniquely identifies the file in a given file system. The pair st_ino and st_dev uniquely identifies regular files.

st_dev

This field uniquely identifies the file system that contains the file. Its value may be used as input to the ustat(2) function to determine more information about this file system. No other meaning is associated with this value.

st_rdev

This field should be used only by administrative commands. It is valid only for block special or character special files and only has meaning on the system where the file was configured.

st_nlink

This field should be used only by administrative commands.

st_uid

The user ID of the file's owner.

st_gid

The group ID of the file's group.

st_size

For regular files, this is the address of the end of the file. For block special or character special, this is not defined. See also pipe(2).

st_atim

Timestamp when file data was last accessed. Some of the functions that change this member are: creat(2), mknod(2), pipe(2), utime(2), and read(2).

st_mtim

Timestamp when data was last modified. Some of the functions that change this member are: creat(2), mknod(2), pipe(2), utime(2), and write(2).

st_ctim

Timestamp when file status was last changed. Some of the functions that change this member are: chmod(2), chown(2), creat(2), link(2), mknod(2), pipe(2), rename(2), unlink(2), utime(2), and write(2).


Note -  For compatibility with earlier versions of this structure the macro st_atime is defined to access the seconds component of the st_atim timestamp. Similarly the macros st_mtime and st_ctime are defined to provide access to the seconds components of the st_mtim and st_ctim timestamps respectively.
st_blksize

A hint as to the “best” unit size for I/O operations. This field is not defined for block special or character special files.

st_blocks

The total number of physical blocks of size 512 bytes actually allocated on disk. This field is not defined for block special or character special files.

st_fstype

A null-terminated string that uniquely identifies the type of the filesystem that contains the file.

Return Values

Upon successful completion, 0 is returned. Otherwise, −1 is returned and errno is set to indicate the error.

Errors

The stat(), fstat(), lstat(), and fstatat() functions will fail if:

EIO

An error occurred while reading from the file system.

EOVERFLOW

The file size in bytes or the number of blocks allocated to the file or the file serial number cannot be represented correctly in the structure pointed to by buf.

The stat(), lstat(), and fstatat() functions will fail if:

EACCES

Search permission is denied for a component of the path prefix.

EFAULT

The buf or path argument points to an illegal address.

EINTR

A signal was caught during the execution of the stat() or lstat() function.

ELOOP

A loop exists in symbolic links encountered during the resolution of the path argument.

ENAMETOOLONG

The length of the path argument exceeds {PATH_MAX}, or the length of a path component exceeds {NAME_MAX} while _POSIX_NO_TRUNC is in effect.

ENOENT

A component of path does not name an existing file or path is an empty string.

ENOLINK

The path argument points to a remote machine and the link to that machine is no longer active.

ENOTDIR

A component of the path prefix is not a directory, or the fildes argument does not refer to a valid directory when given a non-null relative path.

The fstat() and fstatat() functions will fail if:

EBADF

The fildes argument is not a valid open file descriptor. The fildes argument to fstatat() can also have the valid value of AT_FDCWD.

EFAULT

The buf argument points to an illegal address.

EINTR

A signal was caught during the execution of the fstat() function.

ENOLINK

The fildes argument points to a remote machine and the link to that machine is no longer active.

The stat(), fstat(), and lstat() functions may fail if:

EOVERFLOW

One of the members is too large to store in the stat structure pointed to by buf.

The stat() and lstat() functions may fail if:

ELOOP

More than {SYMLOOP_MAX} symbolic links were encountered during the resolution of the path argument.

ENAMETOOLONG

As a result of encountering a symbolic link in resolution of the path argument, the length of the substituted pathname strings exceeds {PATH_MAX}.

The stat() and fstatat() functions may fail if:

ENXIO

The path argument names a character or block device special file and the corresponding I/O device has been retired by the fault management framework.

Examples

Example 1 Use stat() to obtain file status information.

The following example shows how to obtain file status information for a file named /home/cnd/mod1. The structure variable buffer is defined for the stat structure.

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

struct stat buffer;
int         status;
...
status = stat("/home/cnd/mod1", &buffer);
Example 2 Use stat() to get directory information.

The following example fragment gets status information for each entry in a directory. The call to the stat() function stores file information in the stat structure pointed to by statbuf. The lines that follow the stat() call format the fields in the stat structure for presentation to the user of the program.

#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
#include <pwd.h>
#include <grp.h>
#include <time.h>
#include <locale.h>
#include <langinfo.h>
#include <stdio.h>
#include <stdint.h>

struct dirent *dp;
struct stat   statbuf;
struct passwd *pwd;
struct group  *grp;
struct tm     *tm;
char          datestring[256];
...
/* Loop through directory entries */
while ((dp = readdir(dir)) != NULL) {
    /* Get entry's information. */
    if (stat(dp->d_name, &statbuf) == -1)
        continue;

    /* Print out type, permissions, and number of links. */
    printf("%10.10s", mode_to_string(statbuf.st_mode));
    printf("%4d", statbuf.st_nlink);

    /* Print out owners name if it is found using getpwuid(). */
    if ((pwd = getpwuid(statbuf.st_uid)) != NULL)
        printf(" %-8.8s", pwd->pw_name);
    else
        printf(" %-8d", statbuf.st_uid);

    /* Print out group name if it's found using getgrgid(). */
    if ((grp = getgrgid(statbuf.st_gid)) != NULL)
        printf(" %-8.8s", grp->gr_name);
    else
        printf(" %-8d", statbuf.st_gid);

    /* Print size of file. */
    printf(" %9jd", (intmax_t)statbuf.st_size);
    tm = localtime(&statbuf.st_mtime);

    /* Get localized date string. */
    strftime(datestring, sizeof(datestring), nl_langinfo(D_T_FMT), tm);

    printf(" %s %s\n", datestring, dp->d_name);
 }
Example 3 Use fstat() to obtain file status information.

The following example shows how to obtain file status information for a file named /home/cnd/mod1. The structure variable buffer is defined for the stat structure. The /home/cnd/mod1 file is opened with read/write privileges and is passed to the open file descriptor fildes.

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

struct stat buffer;
int         status;
...
fildes = open("/home/cnd/mod1", O_RDWR);
status = fstat(fildes, &buffer);
Example 4 Use lstat() to obtain symbolic link status information.

The following example shows how to obtain status information for a symbolic link named /modules/pass1. The structure variable buffer is defined for the stat structure. If the path argument specified the filename for the file pointed to by the symbolic link (/home/cnd/mod1), the results of calling the function would be the same as those returned by a call to the stat() function.

#include <sys/stat.h>

struct stat buffer;
int         status;
...
status = lstat("/modules/pass1", &buffer);

Usage

If chmod() or fchmod() is used to change the file group owner permissions on a file with non-trivial ACL entries, only the ACL mask is set to the new permissions and the group owner permission bits in the file's mode field (defined in mknod(2)) are unchanged. A non-trivial ACL entry is one whose meaning cannot be represented in the file's mode field alone. The new ACL mask permissions might change the effective permissions for additional users and groups that have ACL entries on the file.

The stat(), fstat(), and lstat() functions have transitional interfaces for 64-bit file offsets. See lf64(7).

Attributes

See attributes(7) for descriptions of the following attributes:

ATTRIBUTE TYPE
ATTRIBUTE VALUE
Interface Stability
Committed
MT-Level
Async-Signal-Safe
Standard
See below.

See standards(7) for descriptions of the following standards:

INTERFACES
APPLICABLE STANDARDS
  • stat()
  • lstat()
  • fstat()
  • POSIX.1-1990 through 2008,
  • SUS through SUSv4,
  • XPG1 through XPG7
  • fstatat()
  • SUSv4,
  • XPG7

See Also

access(2), chmod(2), chown(2), creat(2), link(2), mknod(2), pipe(2), read(2), time(2), unlink(2), utime(2), write(2), fattach(3C), stat.h(3HEAD), attributes(7), fsattr(7), lf64(7), standards(7)

Notes

Some file systems additionally provide a file creation timestamp, in addition to the timestamps described above. This timestamp is not available through the interfaces described on this page, but must instead be retrieved using the getattrat(3C) function as the A_CRTIME system attribute.

For testing purposes only, the behavior of these interfaces can be changed when used by a 32-bit programs on systems where the timestamps will not fit into the st_atime, st_mtime, or st_ctime stat structure fields. If this configuration line is present in /etc/system:

set stat_timestamp32 = 1

A ceiling value will be substituted for the timestamps which do not fit in the returned stat structure fields, and no EOVERFLOW error will be returned. This option allows a limited set of testing to be performed on systems with an advanced date/time where some 32-bit programs may still be in use. This option exists purely for testing purposes; some parts of Oracle Solaris will not behave correctly when this is used on systems with the date advanced past 03:14:07 UTC January 19, 2038. No support calls will be taken on such issues.

History

The stat(), lstat(), and fstat() functions have been included in all Sun and Oracle releases of Solaris.

The fstatat() function was added to Solaris in the Solaris 9 release.