Movatterモバイル変換


[0]ホーム

URL:


man7.org > Linux >man-pages

Linux/UNIX system programming training


stat(2) — Linux manual page

NAME |LIBRARY |SYNOPSIS |DESCRIPTION |RETURN VALUE |ERRORS |STANDARDS |HISTORY |EXAMPLES |SEE ALSO |COLOPHON

stat(2)                    System Calls Manualstat(2)

NAME        top

       stat, fstat, lstat, fstatat - get file status

LIBRARY        top

       Standard C library (libc,-lc)

SYNOPSIS        top

#include <sys/stat.h>int stat(const char *restrictpath,struct stat *restrictstatbuf);int fstat(intfd, struct stat *statbuf);int lstat(const char *restrictpath,struct stat *restrictstatbuf);#include <fcntl.h>/* Definition ofAT_*constants */#include <sys/stat.h>int fstatat(intdirfd, const char *restrictpath,struct stat *restrictstatbuf, intflags);   Feature Test Macro Requirements for glibc (seefeature_test_macros(7)):lstat():           /* Since glibc 2.20 */ _DEFAULT_SOURCE               || _XOPEN_SOURCE >= 500               || /* Since glibc 2.10: */ _POSIX_C_SOURCE >= 200112L               || /* glibc 2.19 and earlier */ _BSD_SOURCEfstatat():           Since glibc 2.10:               _POSIX_C_SOURCE >= 200809L           Before glibc 2.10:               _ATFILE_SOURCE

DESCRIPTION        top

       These functions return information about a file, in the buffer       pointed to bystatbuf.  No permissions are required on the file       itself, but—in the case ofstat(),fstatat(), andlstat()—execute       (search) permission is required on all of the directories inpath       that lead to the file.stat() andfstatat() retrieve information about the file pointed       to bypath; the differences forfstatat() are described below.lstat() is identical tostat(), except that ifpath is a symbolic       link, then it returns information about the link itself, not the       file that the link refers to.fstat() is identical tostat(), except that the file about which       information is to be retrieved is specified by the file descriptorfd.The stat structure       All of these system calls return astat structure (seestat(3type)).Note: for performance and simplicity reasons, different fields in       thestat structure may contain state information from different       moments during the execution of the system call.  For example, ifst_mode orst_uid is changed by another process by callingchmod(2) orchown(2),stat() might return the oldst_mode together       with the newst_uid, or the oldst_uid together with the newst_mode.fstatat()       Thefstatat() system call is a more general interface for       accessing file information which can still provide exactly the       behavior of each ofstat(),lstat(), andfstat().       Ifpath is relative, then it is interpreted relative to the       directory referred to by the file descriptordirfd (rather than       relative to the current working directory of the calling process,       as is done bystat() andlstat() for a relative pathname).       Ifpath is relative anddirfd is the special valueAT_FDCWD, thenpath is interpreted relative to the current working directory of       the calling process (likestat() andlstat()).       Ifpath is absolute, thendirfd is ignored.flags can either be 0, or include one or more of the following       flags ORed:AT_EMPTY_PATH(since Linux 2.6.39)              Ifpath is an empty string (or NULL, since Linux 6.11)              operate on the file referred to bydirfd (which may have              been obtained using theopen(2)O_PATHflag).  In this              case,dirfd can refer to any type of file, not just a              directory, and the behavior offstatat() is similar to that              offstat().  Ifdirfd isAT_FDCWD, the call operates on the              current working directory.  This flag is Linux-specific;              define_GNU_SOURCEto obtain its definition.AT_NO_AUTOMOUNT(since Linux 2.6.38)              Don't automount the terminal ("basename") component ofpath.  Since Linux 3.1 this flag is ignored.  Since Linux              4.11 this flag is implied.AT_SYMLINK_NOFOLLOW              Ifpath is a symbolic link, do not dereference it: instead              return information about the link itself, likelstat().              (By default,fstatat() dereferences symbolic links, likestat().)       Seeopenat(2) for an explanation of the need forfstatat().

RETURN VALUE        top

       On success, zero is returned.  On error, -1 is returned, anderrno       is set to indicate the error.

ERRORS        top

EACCESSearch permission is denied for one of the directories in              the path prefix ofpath.  (See alsopath_resolution(7).)EBADFfd is not a valid open file descriptor.EBADF(fstatat())path is relative butdirfd is neitherAT_FDCWD              nor a valid file descriptor.EFAULTBad address.EINVAL(fstatat()) Invalid flag specified inflags.ELOOPToo many symbolic links encountered while traversing the              path.ENAMETOOLONGpath is too long.ENOENTA component ofpath does not exist or is a dangling              symbolic link.ENOENTpath is an empty string andAT_EMPTY_PATHwas not specified              inflags.ENOMEMOut of memory (i.e., kernel memory).ENOTDIR              A component of the path prefix ofpath is not a directory.ENOTDIR              (fstatat())path is relative anddirfd is a file descriptor              referring to a file other than a directory.EOVERFLOWpath orfd refers to a file whose size, inode number, or              number of blocks cannot be represented in, respectively,              the typesoff_t,ino_t, orblkcnt_t.  This error can occur              when, for example, an application compiled on a 32-bit              platform without-D_FILE_OFFSET_BITS=64 callsstat() on a              file whose size exceeds(1<<31)-1 bytes.

STANDARDS        top

       POSIX.1-2008.

HISTORY        top

stat()fstat()lstat()              SVr4, 4.3BSD, POSIX.1-2001.fstatat()              POSIX.1-2008.  Linux 2.6.16, glibc 2.4.       According to POSIX.1-2001,lstat() on a symbolic link need return       valid information only in thest_size field and the file type of       thest_mode field of thestat structure.  POSIX.1-2008 tightens       the specification, requiringlstat() to return valid information       in all fields except the mode bits inst_mode.       Use of thest_blocks andst_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.)C library/kernel differences       Over time, increases in the size of thestat structure have led to       three successive versions ofstat():sys_stat() (slot__NR_oldstat),sys_newstat() (slot__NR_stat), andsys_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 forfstat() andlstat().       The kernel-internal versions of thestat structure dealt with by       the different versions are, respectively:__old_kernel_stat              The original structure, with rather narrow fields, and no              padding.stat   Largerst_ino field and padding added to various parts of              the structure to allow for future expansion.stat64 Even largerst_ino field, largerst_uid andst_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 glibcstat() 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 singlestat() system call and the kernel deals with astat structure that       contains fields of a sufficient size.       The underlying system call employed by the glibcfstatat() wrapper       function is actually calledfstatat64() or, on some architectures,newfstatat().

EXAMPLES        top

       The following program callslstat() and displays selected fields       in the returnedstat structure.       #include <stdint.h>       #include <stdio.h>       #include <stdlib.h>       #include <sys/stat.h>       #include <sys/sysmacros.h>       #include <time.h>       int       main(int argc, char *argv[])       {           struct stat sb;           if (argc != 2) {               fprintf(stderr, "Usage: %s <path>\n", argv[0]);               exit(EXIT_FAILURE);           }           if (lstat(argv[1], &sb) == -1) {               perror("lstat");               exit(EXIT_FAILURE);           }           printf("ID of containing device:  [%x,%x]\n",                  major(sb.st_dev),                  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:            %ju\n", (uintmax_t) sb.st_ino);           printf("Mode:                     %jo (octal)\n",                  (uintmax_t) sb.st_mode);           printf("Link count:               %ju\n", (uintmax_t) sb.st_nlink);           printf("Ownership:                UID=%ju   GID=%ju\n",                  (uintmax_t) sb.st_uid, (uintmax_t) sb.st_gid);           printf("Preferred I/O block size: %jd bytes\n",                  (intmax_t) sb.st_blksize);           printf("File size:                %jd bytes\n",                  (intmax_t) sb.st_size);           printf("Blocks allocated:         %jd\n",                  (intmax_t) 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);       }

SEE ALSO        top

ls(1),stat(1),access(2),chmod(2),chown(2),readlink(2),statx(2),utime(2),stat(3type),capabilities(7),inode(7),symlink(7)

COLOPHON        top

       This page is part of theman-pages (Linux kernel and C library       user-space interface documentation) project.  Information about       the project can be found at        ⟨https://www.kernel.org/doc/man-pages/⟩.  If you have a bug report       for this manual page, see       ⟨https://git.kernel.org/pub/scm/docs/man-pages/man-pages.git/tree/CONTRIBUTING⟩.       This page was obtained from the tarball man-pages-6.15.tar.gz       fetched from       ⟨https://mirrors.edge.kernel.org/pub/linux/docs/man-pages/⟩ on       2025-08-11.  If you discover any rendering problems in this HTML       version of the page, or you believe there is a better or more up-       to-date source for the page, or you have corrections or       improvements to the information in this COLOPHON (which isnot       part of the original manual page), send a mail to       man-pages@man7.orgLinux man-pages 6.15            2025-05-17stat(2)

Pages that refer to this page:bash(1)find(1)fuser(1)lsfd(1)pv(1)rsync(1)stat(1)strace(1)systemd-analyze(1)access(2)chmod(2)fallocate(2)fanotify_init(2)futimesat(2)getxattr(2)ioctl_nsfs(2)link(2)listxattr(2)mkdir(2)mknod(2)mount(2)NS_GET_USERNS(2const)open(2)pivot_root(2)readlink(2)removexattr(2)setxattr(2)spu_create(2)statfs(2)statx(2)symlink(2)syscalls(2)truncate(2)umask(2)ustat(2)utime(2)utimensat(2)dirfd(3)euidaccess(3)fseek(3)ftok(3)fts(3)ftw(3)getfilecon(3)getseuserbyname(3)glob(3)isatty(3)isfdtype(3)makedev(3)mkfifo(3)readdir(3)readline(3)sd_is_fifo(3)sd_pidfd_get_inode_id(3)selabel_lookup_best_match(3)setfilecon(3)shm_open(3)stat(3type)ttyname(3)fuse(4)nfs(5)proc(5)proc_pid_mountinfo(5)selabel_file(5)sysfs(5)inode(7)inotify(7)landlock(7)namespaces(7)path_resolution(7)pipe(7)shm_overview(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)



HTML rendering created 2025-09-06 byMichael Kerrisk, author ofThe Linux Programming Interface.

For details of in-depthLinux/UNIX system programming training courses that I teach, lookhere.

Hosting byjambit GmbH.

Cover of TLPI


[8]ページ先頭

©2009-2025 Movatter.jp