본문 바로가기

study/42Seoul

[C] stat / lstat / fstat 함수

 

파일 상태(정보) 가져오기
지정한 파일의 정보를 담고 있는 stat 구조체를 통해 정보를 얻을 수 있는 시스템 함수들
ls -al 명령어로 알 수 있는 내용들을 대부분 알 수 있다.



#include <sys/stat.h>

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

 

구조체 stat

- 함수의 인자로 들어가는 struct stat

 

- st_dev - 파일을 포함하는 디바이스 번호
- st_mode - 파일의 모드 (접근권한) - 파일 종류 비트 마스크로 표시됨
- st_nlink - 파일의 하드링크 수
- st_ino - 파일의 inode 번호
- st_uid - user ID
- st_gid - group ID
- st_rdev - 디바이스 아이디(특수 파일인 경우)
- timespec st_atimespec;  - 최종 접근 시간 (access time)
- timespec st_mtimespec;  - 최종 수정 시간 (modification time)
- timespec st_ctimespec;  - 최종 상태 변경 시간 (change time)
- timespec st_birthtimespec;  - 파일 생성 시간(birth time)
- st_size - 파일의 사이즈(byte)
- st_blocks - 파일에 할당한 블럭의 수
- st_blksize - 효율적인 I/O 파일 블럭 사이즈
                            : 512바이트 단위로 파일에 할당된 실제 블록 수
                                짧은 심볼릭 링크들이 inode에 저장되기 때문에, 이 숫자는 0일 수 있다.
- st_flags - 파일에 대한 사용자 정의 플래그
- st_gen 파일 생성 번호

 

 

when _DARWIN_FEATURE_64_BIT_INODE is defined (MAC OSX 10.5부터 해당)

 

struct stat { /* when _DARWIN_FEATURE_64_BIT_INODE is defined */
         dev_t           st_dev;           /* ID of device containing file */
         mode_t          st_mode;          /* Mode of file (see below) */
         nlink_t         st_nlink;         /* Number of hard links */
         ino_t           st_ino;           /* File serial number */
         uid_t           st_uid;           /* User ID of the file */
         gid_t           st_gid;           /* Group ID of the file */
         dev_t           st_rdev;          /* Device ID */
         struct timespec st_atimespec;     /* time of last access */
         struct timespec st_mtimespec;     /* time of last data modification */
         struct timespec st_ctimespec;     /* time of last status change */
         struct timespec st_birthtimespec; /* time of file creation(birth) */
         off_t           st_size;          /* file size, in bytes */
         blkcnt_t        st_blocks;        /* blocks allocated for file */
         blksize_t       st_blksize;       /* optimal blocksize for I/O */
         uint32_t        st_flags;         /* user defined flags for file */
         uint32_t        st_gen;           /* file generation number */
         int32_t         st_lspare;        /* RESERVED: DO NOT USE! */
         int64_t         st_qspare[2];     /* RESERVED: DO NOT USE! */
     };

 

when _DARWIN_FEATURE_64_BIT_INODE is NOT defined

더보기
struct stat { /* when _DARWIN_FEATURE_64_BIT_INODE is NOT defined */
         dev_t    st_dev;    /* device inode resides on */
         ino_t    st_ino;    /* inode's number */
         mode_t   st_mode;   /* inode protection mode */
         nlink_t  st_nlink;  /* number of hard links to the file */
         uid_t    st_uid;    /* user-id of owner */
         gid_t    st_gid;    /* group-id of owner */
         dev_t    st_rdev;   /* device type, for special file inode */
         struct timespec st_atimespec;  /* time of last access */
         struct timespec st_mtimespec;  /* time of last data modification */
         struct timespec st_ctimespec;  /* time of last file status change */
         off_t    st_size;   /* file size, in bytes */
         quad_t   st_blocks; /* blocks allocated for file */
         u_long   st_blksize;/* optimal file sys I/O ops blocksize */
         u_long   st_flags;  /* user defined flags for file */
         u_long   st_gen;    /* file generation number */
     };

return value

  • 성공: 0 → 파일의 정보를 buf(stat 구조체)에 복사
  • 실패: -1 → errno 설정

stat

파일 정보를 path로 지정

  • 파일의 읽기, 쓰기 또는 실행 권한은 필요하지 않지만 파일로 이어지는 경로 이름에 나열된 모든 디렉터리는 검색 가능해야 합니다.
  • path가 심볼릭 링크일 경우 → 링크가 참조하는 파일에 대한 정보를 반환

lstat

  • 파일 정보를 path로 지정
    • path가 심볼릭 링크인 경우를 제외하고 stat() 함수와 동일
  • path가 심볼릭 링크일 경우 → 링크에 대한 정보를 반환
    • st_mode 는 파일 형식 매크로와 함께 사용될 때 의미 있는 정보를 포함
    • st_size 는 심볼릭 링크에 포함된 경로 이름의 길이를 포함
      • File mode bits와 구조체 stat의 나머지 멤버들은 명시 X
      • st_size에서 반환되는 값은 심볼릭 링크의 내용 길이이며, 따라오는 null은 계산 X

fstat

  • 파일 정보를 fildes로 지정
    • fildes(fd) - open(2) 등으로 생성한 file descriptor

ERROR

더보기
ERRORS
     The fstat() system call will fail if:

     [EBADF]            fildes is not a valid open file descriptor.

     [EFAULT]           Sb points to an invalid address.

     [EIO]              An I/O error occurs while reading from or writing to the file system.

     The lstat() and stat() system calls will fail if:

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

     [EFAULT]           Sb or name points to an invalid address.

     [EIO]              An I/O error occurs while reading from or writing to the file system.

     [ELOOP]            Too many symbolic links are encountered in translating the pathname.  This is taken to be indicative
                        of a looping symbolic link.

     [ENAMETOOLONG]     A component of a pathname exceeds {NAME_MAX} characters, or an entire path name exceeds {PATH_MAX}
                        characters.

     [ENOENT]           The named file does not exist.

     [ENOTDIR]          A component of the path prefix is not a directory.

     The fstat(), lstat(), and stat() system calls will fail if:

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

     In addition to the errors returned by the stat() and lstat(), fstatat() may fail if:

     [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 searching.

     [EINVAL]           The value of the flag argument is not valid.

     [ENOTDIR]          The path argument is not an absolute path and fd is neither AT_FDCWD nor a file descriptor associated
                        with a directory.

 

참고 사이트

man 2 stat
 

C/C++ stat(2), lstat(2), fstat(2)

stat 함수 기능 지정한 파일의 정보를 담고 있는 stat 구조체를 얻어주는 시스템 함수입니다. stat(2) 파일을 filepath 로 지정합니다. fstat(2) 파일을 fd 넘버로 지정합니다. lstat(2) 파일을 filepath 로 지정

bubble-dev.tistory.com

 

'study > 42Seoul' 카테고리의 다른 글

[minishell] parsing - 1.preprocessing  (3) 2023.01.30