Stat(2) — linux man page
Содержание:
CONFORMING TO top
stat(), fstat(), lstat(): SVr4, 4.3BSD, POSIX.1-2001, POSIX.1.2008.
fstatat(): POSIX.1-2008.
According to POSIX.1-2001, lstat() on a symbolic link need return
valid information only in the st_size field and the file type of the
st_mode field of the stat structure. POSIX.1-2008 tightens the
specification, requiring lstat() to return valid information in all
fields except the mode bits in st_mode.
Use of the st_blocks and st_blksize fields may be less portable.
(They were introduced in BSD. The interpretation differs between
systems, and possibly on a single system when NFS mounts are
involved.)
ERRORS top
EACCES Search permission is denied for one of the directories in the
path prefix of pathname. (See also path_resolution(7).)
EBADF fd is not a valid open file descriptor.
EFAULT Bad address.
ELOOP Too many symbolic links encountered while traversing the path.
ENAMETOOLONG
pathname is too long.
ENOENT A component of pathname does not exist or is a dangling
symbolic link.
ENOENT pathname is an empty string and AT_EMPTY_PATH was not
specified in flags.
ENOMEM Out of memory (i.e., kernel memory).
ENOTDIR
A component of the path prefix of pathname is not a directory.
EOVERFLOW
pathname or fd refers to a file whose size, inode number, or
number of blocks cannot be represented in, respectively, the
types off_t, ino_t, or blkcnt_t. This error can occur when,
for example, an application compiled on a 32-bit platform
without -D_FILE_OFFSET_BITS=64 calls stat() on a file whose
size exceeds (1<<31)-1 bytes.
The following additional errors can occur for fstatat():
EBADF dirfd is not a valid file descriptor.
EINVAL Invalid flag specified in flags.
ENOTDIR
pathname is relative and dirfd is a file descriptor referring
to a file other than a directory.
stat() functions
The C POSIX library header sys/stat.h, found on POSIX and other Unix-like operating systems, declares the functions, as well as related function called and . The functions take a buffer argument, which is used to return the file attributes. On success, the functions return zero, and on error, −1 is returned and errno is set appropriately.
The and functions take a filename argument. If the file is a symbolic link, returns attributes of the eventual target of the link, while returns attributes of the link itself. The function takes a file descriptor argument instead, and returns attributes of the file that it identifies.
The family of functions was extended to implement large file support. Functions named , and return attributes in a structure, which represents file sizes with a 64-bit type, allowing the functions to work on files 2 GiB and larger (up to 8 EiB). When the macro is defined to 64, these 64-bit functions are available under the original names.
The functions are defined as:
int stat(const char *filename, struct stat *buf); int lstat(const char *filename, struct stat *buf); int fstat(int filedesc, struct stat *buf);
SYNOPSIS top
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
int stat(const char *pathname, struct stat *statbuf);
int fstat(int fd, struct stat *statbuf);
int lstat(const char *pathname, struct stat *statbuf);
#include <fcntl.h> /* Definition of AT_* constants */
#include <sys/stat.h>
int fstatat(int dirfd, const char *pathname, struct stat *statbuf,
int flags);
Feature Test Macro Requirements for glibc (see feature_test_macros(7)):
lstat():
/* glibc 2.19 and earlier */ _BSD_SOURCE
|| /* Since glibc 2.20 */ _DEFAULT_SOURCE
|| _XOPEN_SOURCE >= 500
|| /* Since glibc 2.10: */ _POSIX_C_SOURCE >= 200112L
fstatat():
Since glibc 2.10:
_POSIX_C_SOURCE >= 200809L
Before glibc 2.10:
_ATFILE_SOURCE
ERRORS top
EACCES Search permission is denied for one of the directories in the
path prefix of pathname. (See also path_resolution(7).)
EBADF fd is not a valid open file descriptor.
EFAULT Bad address.
ELOOP Too many symbolic links encountered while traversing the path.
ENAMETOOLONG
pathname is too long.
ENOENT A component of pathname does not exist or is a dangling
symbolic link.
ENOENT pathname is an empty string and AT_EMPTY_PATH was not
specified in flags.
ENOMEM Out of memory (i.e., kernel memory).
ENOTDIR
A component of the path prefix of pathname is not a directory.
EOVERFLOW
pathname or fd refers to a file whose size, inode number, or
number of blocks cannot be represented in, respectively, the
types off_t, ino_t, or blkcnt_t. This error can occur when,
for example, an application compiled on a 32-bit platform
without -D_FILE_OFFSET_BITS=64 calls stat() on a file whose
size exceeds (1<<31)-1 bytes.
The following additional errors can occur for fstatat():
EBADF dirfd is not a valid file descriptor.
EINVAL Invalid flag specified in flags.
ENOTDIR
pathname is relative and dirfd is a file descriptor referring
to a file other than a directory.
SYNOPSIS top
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
int stat(const char *pathname, struct stat *statbuf);
int fstat(int fd, struct stat *statbuf);
int lstat(const char *pathname, struct stat *statbuf);
#include <fcntl.h> /* Definition of AT_* constants */
#include <sys/stat.h>
int fstatat(int dirfd, const char *pathname, struct stat *statbuf,
int flags);
Feature Test Macro Requirements for glibc (see feature_test_macros(7)):
lstat():
/* glibc 2.19 and earlier */ _BSD_SOURCE
|| /* Since glibc 2.20 */ _DEFAULT_SOURCE
|| _XOPEN_SOURCE >= 500
|| /* Since glibc 2.10: */ _POSIX_C_SOURCE >= 200112L
fstatat():
Since glibc 2.10:
_POSIX_C_SOURCE >= 200809L
Before glibc 2.10:
_ATFILE_SOURCE
Examples
stat index.htm
Reports the status of file index.htm, displaying results similar to the following output:
File: `index.htm' Size: 17137 Blocks: 40 IO Block: 8192 regular file Device: 8h/8d Inode: 23161443 Links: 1 Access: (0644/-rw-r--r--) Uid: (17433/comphope) Gid: ( 32/ www) Access: 2007-04-03 09:20:18.000000000 -0600 Modify: 2007-04-01 23:13:05.000000000 -0600 Change: 2007-04-02 16:36:21.000000000 -0600
stat -f /dev/sda
With the -f option, stat can return the status of an entire file system. Here, it returns the status of the first hard disk. Output will resemble the following:
File: "/dev/sda"
ID: 0 Namelen: 255 Type: tmpfs
Block size: 4096 Fundamental block size: 4096
Blocks: Total: 2560 Free: 2560 Available: 2560
Inodes: Total: 126428 Free: 125966
stat --format "%A" /var/log/syslog
Display only the access restrictions, in human-readable form, of the system log /var/log/syslog. Output will resemble the following:
-rw-r-----
…which indicates that the file is readable and writable by root, readable by the owning group (in this case the admin group), and not accessible at all by others.
Member types[edit]
Data types defined in the header include:
struct stat {
dev_t st_dev; /* ID of device containing file */
ino_t st_ino; /* inode number */
mode_t st_mode; /* protection */
nlink_t st_nlink; /* number of hard links */
uid_t st_uid; /* user ID of owner */
gid_t st_gid; /* group ID of owner */
dev_t st_rdev; /* device ID (if special file) */
off_t st_size; /* total size, in bytes */
blksize_t st_blksize; /* blocksize for file system I/O */
blkcnt_t st_blocks; /* number of blocks allocated */
time_t st_atime; /* time of last access */
time_t st_mtime; /* time of last modification */
time_t st_ctime; /* time of last status change */
};
ERRORS top
EACCES (statvfs()) Search permission is denied for a component of the
path prefix of path. (See also path_resolution(7).)
EBADF (fstatvfs()) fd is not a valid open file descriptor.
EFAULT Buf or path points to an invalid address.
EINTR This call was interrupted by a signal; see signal(7).
EIO An I/O error occurred while reading from the filesystem.
ELOOP (statvfs()) Too many symbolic links were encountered in
translating path.
ENAMETOOLONG
(statvfs()) path is too long.
ENOENT (statvfs()) The file referred to by path does not exist.
ENOMEM Insufficient kernel memory was available.
ENOSYS The filesystem does not support this call.
ENOTDIR
(statvfs()) A component of the path prefix of path is not a
directory.
EOVERFLOW
Some values were too large to be represented in the returned
struct.
NOTES top
Timestamp fields
Older kernels and older standards did not support nanosecond
timestamp fields. Instead, there were three timestamp fields—
st_atime, st_mtime, and st_ctime—typed as time_t that recorded
timestamps with one-second precision.
Since kernel 2.5.48, the stat structure supports nanosecond
resolution for the three file timestamp fields. The nanosecond
components of each timestamp are available via names of the form
st_atim.tv_nsec, if suitable feature test macros are defined.
Nanosecond timestamps were standardized in POSIX.1-2008, and,
starting with version 2.12, glibc exposes the nanosecond component
names if _POSIX_C_SOURCE is defined with the value 200809L or
greater, or _XOPEN_SOURCE is defined with the value 700 or greater.
Up to and including glibc 2.19, the definitions of the nanoseconds
components are also defined if _BSD_SOURCE or _SVID_SOURCE is
defined. If none of the aforementioned macros are defined, then the
nanosecond values are exposed with names of the form st_atimensec.
C library/kernel differences
Over time, increases in the size of the stat structure have led to
three successive versions of stat(): sys_stat() (slot __NR_oldstat),
sys_newstat() (slot __NR_stat), and sys_stat64() (slot __NR_stat64)
on 32-bit platforms such as i386. The first two versions were
already present in Linux 1.0 (albeit with different names); the last
was added in Linux 2.4. Similar remarks apply for fstat() and
lstat().
The kernel-internal versions of the stat structure dealt with by the
different versions are, respectively:
__old_kernel_stat
The original structure, with rather narrow fields, and no
padding.
stat Larger st_ino field and padding added to various parts of the
structure to allow for future expansion.
stat64 Even larger st_ino field, larger st_uid and st_gid fields to
accommodate the Linux-2.4 expansion of UIDs and GIDs to 32
bits, and various other enlarged fields and further padding in
the structure. (Various padding bytes were eventually
consumed in Linux 2.6, with the advent of 32-bit device IDs
and nanosecond components for the timestamp fields.)
The glibc stat() wrapper function hides these details from
applications, invoking the most recent version of the system call
provided by the kernel, and repacking the returned information if
required for old binaries.
On modern 64-bit systems, life is simpler: there is a single stat()
system call and the kernel deals with a stat structure that contains
fields of a sufficient size.
The underlying system call employed by the glibc fstatat() wrapper
function is actually called fstatat64() or, on some architectures,
newfstatat().
EXAMPLES top
The following program calls lstat() and displays selected fields in
the returned stat structure.
#include <sys/types.h>
#include <sys/stat.h>
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/sysmacros.h>
int
main(int argc, char *argv[])
{
struct stat sb;
if (argc != 2) {
fprintf(stderr, "Usage: %s <pathname>\n", argv);
exit(EXIT_FAILURE);
}
if (lstat(argv, &sb) == -1) {
perror("lstat");
exit(EXIT_FAILURE);
}
printf("ID of containing device: \n",
(long) major(sb.st_dev), (long) minor(sb.st_dev));
printf("File type: ");
switch (sb.st_mode & S_IFMT) {
case S_IFBLK: printf("block device\n"); break;
case S_IFCHR: printf("character device\n"); break;
case S_IFDIR: printf("directory\n"); break;
case S_IFIFO: printf("FIFO/pipe\n"); break;
case S_IFLNK: printf("symlink\n"); break;
case S_IFREG: printf("regular file\n"); break;
case S_IFSOCK: printf("socket\n"); break;
default: printf("unknown?\n"); break;
}
printf("I-node number: %ld\n", (long) sb.st_ino);
printf("Mode: %lo (octal)\n",
(unsigned long) sb.st_mode);
printf("Link count: %ld\n", (long) sb.st_nlink);
printf("Ownership: UID=%ld GID=%ld\n",
(long) sb.st_uid, (long) sb.st_gid);
printf("Preferred I/O block size: %ld bytes\n",
(long) sb.st_blksize);
printf("File size: %lld bytes\n",
(long long) sb.st_size);
printf("Blocks allocated: %lld\n",
(long long) sb.st_blocks);
printf("Last status change: %s", ctime(&sb.st_ctime));
printf("Last file access: %s", ctime(&sb.st_atime));
printf("Last file modification: %s", ctime(&sb.st_mtime));
exit(EXIT_SUCCESS);
}
Region
WorldwideAfricaAntarcticaAsiaEuropeNorth AmericaOceaniaSouth AmericaAfghanistanÅland IslandsAlbaniaAlgeriaAmerican SamoaAndorraAngolaAnguillaAntarcticaAntigua and BarbudaArgentinaArmeniaArubaAustraliaAustriaAzerbaijanBahamasBahrainBangladeshBarbadosBelarusBelgiumBelizeBeninBermudaBhutanBolivia, Plurinational State ofBonaire, Sint Eustatius and SabaBosnia and HerzegovinaBotswanaBouvet IslandBrazilBritish Indian Ocean TerritoryBrunei DarussalamBulgariaBurkina FasoBurundiCambodiaCameroonCanadaCape VerdeCayman IslandsCentral African RepublicChadChileChinaChristmas IslandCocos (Keeling) IslandsColombiaComorosCongoCongo, the Democratic Republic of theCook IslandsCosta RicaCôte d’IvoireCroatiaCubaCuraçaoCyprusCzech RepublicDenmarkDjiboutiDominicaDominican RepublicEcuadorEgyptEl SalvadorEquatorial GuineaEritreaEstoniaEthiopiaFalkland Islands (Malvinas)Faroe IslandsFijiFinlandFranceFrench GuianaFrench PolynesiaFrench Southern TerritoriesGabonGambiaGeorgiaGermanyGhanaGibraltarGreeceGreenlandGrenadaGuadeloupeGuamGuatemalaGuernseyGuineaGuinea-BissauGuyanaHaitiHeard Island and McDonald IslandsHoly See (Vatican City State)HondurasHong KongHungaryIcelandIndiaIndonesiaIran, Islamic Republic ofIraqIrelandIsle of ManIsraelItalyJamaicaJapanJerseyJordanKazakhstanKenyaKiribatiKorea, Democratic People’s Republic ofKorea, Republic ofKuwaitKyrgyzstanLao People’s Democratic RepublicLatviaLebanonLesothoLiberiaLibyaLiechtensteinLithuaniaLuxembourgMacaoMacedonia, NorthMadagascarMalawiMalaysiaMaldivesMaliMaltaMarshall IslandsMartiniqueMauritaniaMauritiusMayotteMexicoMicronesia, Federated States ofMoldova, Republic ofMonacoMongoliaMontenegroMontserratMoroccoMozambiqueMyanmarNamibiaNauruNepalNetherlandsNew CaledoniaNew ZealandNicaraguaNigerNigeriaNiueNorfolk IslandNorthern Mariana IslandsNorwayOmanPakistanPalauPalestinian Territory, OccupiedPanamaPapua New GuineaParaguayPeruPhilippinesPitcairnPolandPortugalPuerto RicoQatarRéunionRomaniaRussian FederationRwandaSaint BarthélemySaint Helena, Ascension and Tristan da CunhaSaint Kitts and NevisSaint LuciaSaint Martin (French part)Saint Pierre and MiquelonSaint Vincent and the GrenadinesSamoaSan MarinoSao Tome and PrincipeSaudi ArabiaSenegalSerbiaSeychellesSierra LeoneSingaporeSint Maarten (Dutch part)SlovakiaSloveniaSolomon IslandsSomaliaSouth AfricaSouth Georgia and the South Sandwich IslandsSouth SudanSpainSri LankaSudanSurinameSvalbard and Jan MayenSwazilandSwedenSwitzerlandSyrian Arab RepublicTaiwan, Province of ChinaTajikistanTanzania, United Republic ofThailandTimor-LesteTogoTokelauTongaTrinidad and TobagoTunisiaTurkeyTurkmenistanTurks and Caicos IslandsTuvaluUgandaUkraineUnited Arab EmiratesUnited KingdomUnited StatesUnited States Minor Outlying IslandsUruguayUzbekistanVanuatuVenezuela, Bolivarian Republic ofViet NamVirgin Islands, BritishVirgin Islands, U.S.Wallis and FutunaWestern SaharaYemenZambiaZimbabwe
ERRORS top
EACCES Search permission is denied for one of the directories in the
path prefix of pathname. (See also path_resolution(7).)
EBADF fd is not a valid open file descriptor.
EFAULT Bad address.
ELOOP Too many symbolic links encountered while traversing the path.
ENAMETOOLONG
pathname is too long.
ENOENT A component of pathname does not exist or is a dangling
symbolic link.
ENOENT pathname is an empty string and AT_EMPTY_PATH was not
specified in flags.
ENOMEM Out of memory (i.e., kernel memory).
ENOTDIR
A component of the path prefix of pathname is not a directory.
EOVERFLOW
pathname or fd refers to a file whose size, inode number, or
number of blocks cannot be represented in, respectively, the
types off_t, ino_t, or blkcnt_t. This error can occur when,
for example, an application compiled on a 32-bit platform
without -D_FILE_OFFSET_BITS=64 calls stat() on a file whose
size exceeds (1<<31)-1 bytes.
The following additional errors can occur for fstatat():
EBADF dirfd is not a valid file descriptor.
EINVAL Invalid flag specified in flags.
ENOTDIR
pathname is relative and dirfd is a file descriptor referring
to a file other than a directory.
NOTES top
Timestamp fields
Older kernels and older standards did not support nanosecond
timestamp fields. Instead, there were three timestamp fields—
st_atime, st_mtime, and st_ctime—typed as time_t that recorded
timestamps with one-second precision.
Since kernel 2.5.48, the stat structure supports nanosecond
resolution for the three file timestamp fields. The nanosecond
components of each timestamp are available via names of the form
st_atim.tv_nsec, if suitable feature test macros are defined.
Nanosecond timestamps were standardized in POSIX.1-2008, and,
starting with version 2.12, glibc exposes the nanosecond component
names if _POSIX_C_SOURCE is defined with the value 200809L or
greater, or _XOPEN_SOURCE is defined with the value 700 or greater.
Up to and including glibc 2.19, the definitions of the nanoseconds
components are also defined if _BSD_SOURCE or _SVID_SOURCE is
defined. If none of the aforementioned macros are defined, then the
nanosecond values are exposed with names of the form st_atimensec.
C library/kernel differences
Over time, increases in the size of the stat structure have led to
three successive versions of stat(): sys_stat() (slot __NR_oldstat),
sys_newstat() (slot __NR_stat), and sys_stat64() (slot __NR_stat64)
on 32-bit platforms such as i386. The first two versions were
already present in Linux 1.0 (albeit with different names); the last
was added in Linux 2.4. Similar remarks apply for fstat() and
lstat().
The kernel-internal versions of the stat structure dealt with by the
different versions are, respectively:
__old_kernel_stat
The original structure, with rather narrow fields, and no
padding.
stat Larger st_ino field and padding added to various parts of the
structure to allow for future expansion.
stat64 Even larger st_ino field, larger st_uid and st_gid fields to
accommodate the Linux-2.4 expansion of UIDs and GIDs to 32
bits, and various other enlarged fields and further padding in
the structure. (Various padding bytes were eventually
consumed in Linux 2.6, with the advent of 32-bit device IDs
and nanosecond components for the timestamp fields.)
The glibc stat() wrapper function hides these details from
applications, invoking the most recent version of the system call
provided by the kernel, and repacking the returned information if
required for old binaries.
On modern 64-bit systems, life is simpler: there is a single stat()
system call and the kernel deals with a stat structure that contains
fields of a sufficient size.
The underlying system call employed by the glibc fstatat() wrapper
function is actually called fstatat64() or, on some architectures,
newfstatat().
Возвращаемое значениеReturn Value
Каждая из этих функций возвращает 0, если получена информация о состоянии файла.Each of these functions returns 0 if the file-status information is obtained. Возвращаемое значение, равное-1, указывает на ошибку. в этом случае для параметра « еноент » задано значение, указывающее, что не удалось найти имя файла или путь.A return value of -1 indicates an error, in which case errno is set to ENOENT, indicating that the filename or path could not be found. Возвращаемое значение еинвал указывает на недопустимый параметр; в этом случае в этом случае также устанавливается значение еинвал .A return value of EINVAL indicates an invalid parameter; errno is also set to EINVAL in this case.
Дополнительные сведения об этих и других кодах возврата см. в разделе _doserrno, errno, _sys_errlist и _sys_nerr .See _doserrno, errno, _sys_errlist, and _sys_nerr for more information on this, and other, return codes.
Отметка даты файла может быть представлена, если она позже, чем полночь, 1 января 1970 и до 23:59:59, 31 декабря 3000, UTC, если не используется _stat32 или _wstat32или определены _USE_32BIT_TIME_T. в этом случае дата может быть представлена только до 23:59:59 18 января 2038, UTC.The date stamp on a file can be represented if it is later than midnight, January 1, 1970, and before 23:59:59, December 31, 3000, UTC, unless you use _stat32 or _wstat32, or have defined _USE_32BIT_TIME_T, in which case the date can be represented only until 23:59:59 January 18, 2038, UTC.
RATIONALE top
The intent of the paragraph describing ``additional or alternate file
access control mechanisms'' is to allow a secure implementation where
a process with a label that does not dominate the file's label cannot
perform a stat() function. This is not related to read permission; a
process with a label that dominates the file's label does not need
read permission. An implementation that supports write-up operations
could fail fstat() function calls even though it has a valid file
descriptor open for writing.
The lstat() function is not required to update the time-related
fields if the named file is not a symbolic link. While the st_uid,
st_gid, st_atim, st_mtim, and st_ctim members of the stat structure
may apply to a symbolic link, they are not required to do so. No
functions in POSIX.1‐2008 are required to maintain any of these time
fields.
The purpose of the fstatat() function is to obtain the status of
files in directories other than the current working directory without
exposure to race conditions. Any part of the path of a file could be
changed in parallel to a call to stat(), resulting in unspecified
behavior. By opening a file descriptor for the target directory and
using the fstatat() function it can be guaranteed that the file for
which status is returned is located relative to the desired
directory.
Errors
- EACCES
Search permission is denied for one of the directories in the path prefix of path. (See also path_resolution(7).)
EBADF
fd is bad.
EFAULT
Bad address.
ELOOP
Too many symbolic links encountered while traversing the path.
ENAMETOOLONG
path is too long.
ENOENT
A component of path does not exist, or path is an empty string.
ENOMEM
Out of memory (i.e., kernel memory).
ENOTDIR
A component of the path prefix of path is not a directory.
EOVERFLOW
path or fd refers to a file whose size, inode number, or number of blocks cannot be represented in, respectively, the types off_t,
ino_t, or blkcnt_t. This error can occur when, for example, an application compiled on a 32-bit platform without -D_FILE_OFFSET_BITS=64
calls stat() on a file whose size exceeds (1<<31)-1 bytes.
Description
These functions return information about a file. No permissions are required on the file itself, but-in the case of stat() and lstat() —
execute (search) permission is required on all of the directories in path that lead to the file.
stat() stats the file pointed to by path and fills in buf.
lstat() is identical to stat(), except that if path is a symbolic link, then the link itself is stat-ed, not the file that it refers
to.
fstat() is identical to stat(), except that the file to be stat-ed is specified by the file descriptor fd.
All of these system calls return a stat structure, which contains the following fields:
-
struct stat { dev_t st_dev; /* ID of device containing file */ ino_t st_ino; /* inode number */ mode_t st_mode; /* protection */ nlink_t st_nlink; /* number of hard links */ uid_t st_uid; /* user ID of owner */ gid_t st_gid; /* group ID of owner */ dev_t st_rdev; /* device ID (if special file) */ off_t st_size; /* total size, in bytes */ blksize_t st_blksize; /* blocksize for file system I/O */ blkcnt_t st_blocks; /* number of 512B blocks allocated */ time_t st_atime; /* time of last access */ time_t st_mtime; /* time of last modification */ time_t st_ctime; /* time of last status change */ }; - The st_dev field describes the device on which this file resides. (The major(3) and minor(3) macros may be useful to decompose the
device ID in this field.)
The st_rdev field describes the device that this file (inode) represents.
The st_size field gives the size of the file (if it is a regular file or a symbolic link) in bytes. The size of a symbolic link is the length of the
pathname it contains, without a terminating null byte.
The st_blocks field indicates the number of blocks allocated to the file, 512-byte units. (This may be smaller than st_size/512 when the file
has holes.)
The st_blksize field gives the «preferred» blocksize for efficient file system I/O. (Writing to a file in smaller chunks may cause an inefficient
read-modify-rewrite.)
Not all of the Linux file systems implement all of the time fields. Some file system types allow mounting in such a way that file and/or directory accesses
do not cause an update of the st_atime field. (See noatime, nodiratime, and relatime in mount(8), and related information in
mount(2).) In addition, st_atime is not updated if a file is opened with the O_NOATIME; see open(2).
The field st_atime is changed by file accesses, for example, by execve(2), mknod(2), pipe(2), utime(2) and read(2)
(of more than zero bytes). Other routines, like mmap(2), may or may not update st_atime.
The field st_mtime is changed by file modifications, for example, by (2), truncate(2), (2) and write(2) (of
more than zero bytes). Moreover, st_mtime of a directory is changed by the creation or deletion of files in that directory. The st_mtime field is
not changed for changes in owner, group, hard link count, or mode.
The field st_ctime is changed by writing or by setting inode information (i.e., owner, group, link count, mode, etc.).
The following POSIX macros are defined to check the file type using the st_mode field:
S_ISREG(m)
is it a regular file?
S_ISDIR(m)
directory?
S_ISCHR(m)
character device?
S_ISBLK(m)
block device?
S_ISFIFO(m)
FIFO (named pipe)?
S_ISLNK(m)
symbolic link? (Not in POSIX.1-1996.)
S_ISSOCK(m)
socket? (Not in POSIX.1-1996.)
The following flags are defined for the st_mode field:
The set-group-ID bit (S_ISGID) has several special uses. For a directory it indicates that BSD semantics is to be used for that directory: files
created there inherit their group ID from the directory, not from the effective group ID of the creating process, and directories created there will also get
the S_ISGID bit set. For a file that does not have the group execution bit (S_IXGRP) set, the set-group-ID bit indicates mandatory file/record
locking.
The sticky bit (S_ISVTX) on a directory means that a file in that directory can be renamed or deleted only by the owner of the file, by the owner of
the directory, and by a privileged process.
COLOPHON top
This page is part of release 5.08 of the Linux man-pages project. A
description of the project, information about reporting bugs, and the
latest version of this page, can be found at
https://www.kernel.org/doc/man-pages/.
Linux 2020-08-13 STAT(2)
Pages that refer to this page:
bash(1),
find(1),
pv(1),
stat(1),
access(2),
chmod(2),
creat(2),
faccessat(2),
fallocate(2),
fchmod(2),
fchmodat(2),
fgetxattr(2),
flistxattr(2),
fremovexattr(2),
fsetxattr(2),
fstatfs(2),
fstatfs64(2),
ftruncate(2),
ftruncate64(2),
futimesat(2),
getxattr(2),
lgetxattr(2),
link(2),
linkat(2),
listxattr(2),
llistxattr(2),
lremovexattr(2),
lsetxattr(2),
mkdir(2),
mkdirat(2),
mknod(2),
mknodat(2),
mount(2),
open(2),
openat(2),
pivot_root(2),
readlink(2),
readlinkat(2),
removexattr(2),
setxattr(2),
spu_create(2),
statfs(2),
statfs64(2),
statx(2),
syscalls(2),
truncate(2),
truncate64(2),
umask(2),
ustat(2),
utime(2),
utimensat(2),
utimes(2),
eaccess(3),
euidaccess(3),
fgetfilecon(3),
fgetfilecon_raw(3),
fsetfilecon(3),
fsetfilecon_raw(3),
ftok(3),
fts(3),
fts_children(3),
fts_close(3),
fts_open(3),
fts_read(3),
fts_set(3),
ftw(3),
futimens(3),
getfilecon(3),
getfilecon_raw(3),
getseuserbyname(3),
glob(3),
globfree(3),
gnu_dev_major(3),
gnu_dev_makedev(3),
gnu_dev_minor(3),
isfdtype(3),
lgetfilecon(3),
lgetfilecon_raw(3),
lsetfilecon(3),
lsetfilecon_raw(3),
major(3),
makedev(3),
minor(3),
mkfifo(3),
mkfifoat(3),
nftw(3),
readline(3),
setfilecon(3),
setfilecon_raw(3),
fuse(4),
nfs(5),
proc(5),
procfs(5),
sysfs(5),
inode(7),
inotify(7),
namespaces(7),
path_resolution(7),
pipe(7),
signal-safety(7),
spufs(7),
symlink(7),
time(7),
user_namespaces(7),
xattr(7),
lsof(8),
umount(8),
xfs_db(8),
xfs_io(8)
ERRORS top
These functions shall fail if:
EACCES Search permission is denied for a component of the path
prefix.
EIO An error occurred while reading from the file system.
ELOOP A loop exists in symbolic links encountered during resolution
of the path argument.
ENAMETOOLONG
The length of a component of a pathname is longer than
{NAME_MAX}.
ENOENT A component of path does not name an existing file or path is
an empty string.
ENOTDIR
A component of the path prefix names an existing file that is
neither a directory nor a symbolic link to a directory, or the
path argument contains at least one non-<slash> character and
ends with one or more trailing <slash> characters and the last
pathname component names an existing file that is neither a
directory nor a symbolic link to a directory.
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 fstatat() function shall fail if:
EACCES fd was not opened with O_SEARCH and the permissions of the
directory underlying fd do not permit directory searches.
EBADF The path argument does not specify an absolute path and the fd
argument is neither AT_FDCWD nor a valid file descriptor open
for reading or searching.
ENOTDIR
The path argument is not an absolute path and fd is a file
descriptor associated with a non-directory file.
These functions may fail if:
ELOOP More than {SYMLOOP_MAX} symbolic links were encountered during
resolution of the path argument.
ENAMETOOLONG
The length of a pathname exceeds {PATH_MAX}, or pathname
resolution of a symbolic link produced an intermediate result
with a length that exceeds {PATH_MAX}.
EOVERFLOW
A value to be stored would overflow one of the members of the
stat structure.
The fstatat() function may fail if:
EINVAL The value of the flag argument is not valid.
The following sections are informative.
EXAMPLES top
The following program calls lstat() and displays selected fields in
the returned stat structure.
#include <sys/types.h>
#include <sys/stat.h>
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/sysmacros.h>
int
main(int argc, char *argv[])
{
struct stat sb;
if (argc != 2) {
fprintf(stderr, "Usage: %s <pathname>\n", argv);
exit(EXIT_FAILURE);
}
if (lstat(argv, &sb) == -1) {
perror("lstat");
exit(EXIT_FAILURE);
}
printf("ID of containing device: \n",
(long) major(sb.st_dev), (long) minor(sb.st_dev));
printf("File type: ");
switch (sb.st_mode & S_IFMT) {
case S_IFBLK: printf("block device\n"); break;
case S_IFCHR: printf("character device\n"); break;
case S_IFDIR: printf("directory\n"); break;
case S_IFIFO: printf("FIFO/pipe\n"); break;
case S_IFLNK: printf("symlink\n"); break;
case S_IFREG: printf("regular file\n"); break;
case S_IFSOCK: printf("socket\n"); break;
default: printf("unknown?\n"); break;
}
printf("I-node number: %ld\n", (long) sb.st_ino);
printf("Mode: %lo (octal)\n",
(unsigned long) sb.st_mode);
printf("Link count: %ld\n", (long) sb.st_nlink);
printf("Ownership: UID=%ld GID=%ld\n",
(long) sb.st_uid, (long) sb.st_gid);
printf("Preferred I/O block size: %ld bytes\n",
(long) sb.st_blksize);
printf("File size: %lld bytes\n",
(long long) sb.st_size);
printf("Blocks allocated: %lld\n",
(long long) sb.st_blocks);
printf("Last status change: %s", ctime(&sb.st_ctime));
printf("Last file access: %s", ctime(&sb.st_atime));
printf("Last file modification: %s", ctime(&sb.st_mtime));
exit(EXIT_SUCCESS);
}
ctime
It is tempting to believe that ctime originally meant creation time; however, while early Unix did have modification and creation times, the latter was changed to be access time before there was any C structure in which to call anything ctime. The file systems retained just the access time (atime) and modification time (mtime) through 6th edition Unix. The ctime timestamp was added in the file system restructuring that occurred with 7th edition Unix, and has always referred to inode change time. It is updated any time file metadata stored in the inode changes, such as file permissions, file ownership, and creation and deletion of hard links. In some implementations, ctime is affected by renaming a file: Both original Unix, which implemented a renaming by making a link (updating ctime) and then unlinking the old name (updating ctime again) and modern Linux tend to do this.
Unlike atime and mtime, ctime cannot be set to an arbitrary value with utime(), as used by the touch utility, for example. Instead, when utime() is used, or for any other change to the inode other than an update to atime caused by
accessing the file, the ctime value is set to the current time.