Stat ~~~ Powerful tool for accessing File status

Source: Internet
Author: User
Tags bit set lstat posix symlink
Name

Stat, fstat, lstat-Get File status

Synopsis

# Include <sys/types. h>
# Include <sys/STAT. h>
# Include <unistd. h>

Int Stat (const char *Path, Struct stat *Buf);
Int fstat (int
 FD, Struct stat *Buf);
Int lstat (const char *
Path, Struct stat *Buf);

Feature test macro requirements for glibc (seeFeature_test_macros(7 )):

Lstat():
_ Bsd_source | _ xopen_source> = 500 | _ xopen_source & _ xopen_source_extended
|/* Since glibc 2.10: */_ posix_c_source> = 200w.l
Description

These functions return information about a file. No permissions are required on the file itself, but-in the caseStat() AndLstat()-Execute (Search) permission is required on all of the directories inPathThat lead to the file.

Stat() Stats the file pointed toPathAnd fills inBuf.

Lstat() Is identicalStat(), Doesn't that ifPathIs a symbolic link, then the link itself is stat-ed, not the file that it refers.

Fstat() Is identicalStat(), Could t that the file to be stat-ed is specified by the file descriptorFD.

All of these system callreturnStatStructure, 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_devField describes the device on which this file resides. ( Major(3) and Minor(3) macros may be useful to decompose the device ID in this field .)

TheSt_rdevField describes the device that this file (inode) represents.

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

TheSt_blocksField indicates the number of blocks allocated to the file, 512-byte units. (this may be smallerSt_size/512 when the file has holes .)

TheSt_blksizeField 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 ofSt_atimeField. (SeeNoatime,Nodiratime, AndRelatimeInMount(8), and related information inMount(2).) In addition,St_atimeIs not updated if a file is opened withO_noatime; SeeOpen(2 ).

The FieldSt_atimeIs changed by file accesses, for example,Execve(2 ),Mknod(2 ),Pipe(2 ),Utime(2) andRead(2) (of more than zero bytes). Other routines, likeMMAP(2), may or may not updateSt_atime.

The FieldSt_mtimeIs changed by file modifications, for example,Mknod(2 ),Truncate(2 ),Utime(2) andWrite(2) (of more than zero bytes). Moreover,St_mtimeOf a directory is changed by the Creation or Deletion of files in that directory.St_mtimeField isNotChanged for changes in owner, group, hard link count, or mode.

The FieldSt_ctimeIs 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 usingSt_modeField:

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 St_modeField:
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 specified tive group ID of the creating process, and directories created there will also get S_isgidBit 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.

Return Value

On success, zero is returned. on error,-1 is returned, andErrnoIs set appropriately.

Errors
Eacces

Search permission is denied for one of the directories in the path prefixPath. (See alsoPath_resolution(7 ).)

Ebadf

FDIs bad.

Efault

Bad address.

Eloop

Too required symbolic links encountered while traversing the path.

Enametoolong
PathIs too long.
Enoent

A componentPathDoes not exist, orPathIs an empty string.

Enomem

Out of memory (I. e., kernel memory ).

Enotdir
A component of the path prefix PathIs not a directory.
Eoverflow
PathOr FDRefers 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 -D_file_offset_bits = 64CILS Stat() On a file whose size exceeds (1 <31)-1Bytes.
Conforming

These System callconform to svr4, 4.3bsd, POSIX.1-2001.

According to POSIX.1-2001,Lstat() On a symbolic link need return valid information only inSt_sizeField and the file-type component ofSt_modeField ofStatPOSIX.-2008 tightens the specification, requiringLstat() To return valid information in all fields within t the permission bits inSt_mode.

Use ofSt_blocksAndSt_blksizeFields 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 .) if you need to obtain the definition ofBlkcnt_tOrBlksize_tTypes from<Sys/STAT. h>, Then define_ Xopen_sourceWith the value 500 or greater (before includingAnyHeader files ).

POSIX.1-1990 did not describeS_ifmt,S_ifsock,S_iflnk,S_ifreg,S_ifblk,S_ifdir,S_ifchr,S_ififo,S_isvtxConstants, but instead demanded the use of the macrosS_isdir(), Etc.S_if *Constants are present in POSIX.1-2001 and later.

TheS_islnk() AndS_issock() Macros are not in POSIX.1-1996, but both are present in POSIX.1-2001; the former is from svid 4, the latter from susv2.

UNIX V7 (and later systems) hadS_iread,S_iwrite,S_iexec, Where POSIX prescribes the synonymsS_irusr,S_iwusr,S_ixusr.

Other systems

Values that have been (or are) in use on varous systems:
A sticky command appeared in version 32 V at&t UNIX.
Notes

Since kernel 2.5.48,StatStructure supports nanosecond resolution for the three file timestamp fields. glibc exposes the nanosecond component of each field using names of the formSt_atim. TV _nsecIf_ Bsd_sourceOr_ Svid_sourceFeature test macro is defined. These fields are specified in POSIX.1-2008, And, starting with version 2.12, glibc also exposes these field names if_ Posix_c_sourceIs defined with the value 200809l or greater, or_ Xopen_sourceIs defined with the value 700 or greater. If none of the aforementioned macros are defined, then the nanosecond values are exposed with names of the formSt_atimensec. On file systems that do not support subsecond timestamps, the nanosecond fields are returned with the value 0.

On Linux,Lstat() Will generally not trigger automounter action, whereasStat() Will (but seeFstatat(2 )).

For most files under/ProcDirectory,Stat() Does not return the file size inSt_sizeField; instead the field is returned with the value 0.

Underlying kernel interface

Over time, increases in the size of StatStructure have led to three successive versions Stat(): Sys_stat() (Slot _ Nr_oldstat), Sys_newstat() (Slot _ Nr_stat), And Sys_stat64 ()(New in kernel 2.4; slot _ Nr_stat64). 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. Similar remarks apply Fstat() And Lstat().
Example

The following program cballsStat() And displays selected fields in the returnedStatStructure.

#include <sys/types.h>#include <sys/stat.h>#include <time.h>#include <stdio.h>#include <stdlib.h>intmain(int argc, char *argv[]){    struct stat sb;   if (argc != 2) {        fprintf(stderr, "Usage: %s <pathname>\n", argv[0]);        exit(EXIT_FAILURE);    }   if (stat(argv[1], &sb) == -1) {        perror("stat");        exit(EXIT_FAILURE);    }   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);}
See also

Access(2 ),Chmod(2 ),Chown(2 ),Fstatat(2 ),Readlink(2 ),Utime(2 ),Capabilities(7 ),Symlink(7)

Referenced

ACL(5 ),AMD. conf(5 ),ATTR(5 ),CollectD. conf(5 ),CSH(1 ),Dpns_readdirx(3 ),Dump(8 ),Dvips(1 ),Euidaccess(3 ),EV(3 ),Explain(1 ),Explain(3 ),Explain_stat(3 ),Explain_stat_or_die(3 ),Fakeroot-TCP(1 ),Fallocate(2 ),Fastrm(1 ),Fcdircacheloadfile(3 ),Fgetln(3 ),File(1 ),Find(1 ),Fsync(2 ),Ftok(3 ),FTS(3 ),FTW(3 ),Futimesat(2 ),Getfilecon(3 ),Getseuserbyname(3 ),Getxattr(2 ),Glob(3 ),Guestfish(1 ),Guestfs(3 ),Inotify(7 ),Lam_rfposix(2 ),Lfc_readdirxc(3 ),Libinn(3 ),Libinnhist(3 ),Librrd(3 ),Libssh2_sftp_stat_ex(3 ),Link(2 ),Listxattr(2 ),Llvm-ar(1 ),Lslk(8 ),Lsof(8 ),Makedev(3 ),MGP(1 ),Export dir(1 ),Mkdir(2 ),Mkfifo(3 ),Mtree(8 ),Muttrc(5 ),Nfslogsum(8 ),Nhfsstone(8 ),Obsolete(2 ),Path_resolution(2 ),Pax(1 ),Perl561delta(1 ),Perl56delta(1 ),Perlfunc(1 ),Pipe(7 ),Effect_root(2 ),Proc(5 ),Rdist(1 ),Rdup(1 ),Rdup(8 ),Readline(3 ),Removexattr(2 ),Samefile(1 ),Sec(1 ),Setfilecon(3 ),Setmode(3 ),Setxattr(2 ),Sh(1 ),Spax(1 ),Spu_create(2 ),Spufs(2 ),Spufs(7 ),Star(1 ),Stat(1 ),Statfs(2 ),Strmode(3 ),Sudo(8 ),Syscils(2 ),Time(7 ),Umask(2 ),Ustat(2 ),Utimensat(2 ),Watchdog(8 ),Xbiff(1 ),Xdvi(1 ),Xfs_db(8 ),Xfs_io(8 ),Zfs(8 ),Zshmodules(1)

Stat ~~~ Powerful tool for accessing File status

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.