Fundamental of Software Develop/: : Linux System Programming

Linux System Programming: 파일 정보 검색

Jay.P Morgan 2023. 11. 10. 00:00

inode로부터 검색할 수 있는 정보는

파일의 종류, 접근 권한, 하드 링크 개수, 소유자의 UID와 GID, 파일의 크기, 파일 접근 시각, 파일 수정 시각, 파일의 inode 변경 시각

등이다.

 

inode 정보를 검색하면 sys/stat.h 파일에 정의되어 있는 stat 구조체에 저장된다.

 

파일 정보 검색 함수

기능 함수
파일 정보 검색 함수 int stat(const char * pathname, struct stat *statbuf);
  int fstat(int fd, struct stat *statbuf);

 

 

파일 접근 권한 함수

기능 함수
파일 접근 권한 확인  int access(const char *pathname, int mode);
파일 접근 권한 변경  int chmod(const char *pathname, mode_t mode);
   int fchmod(int fd, mode_t mode);

 

 

링크 함수

기능 함수
하드 링크 생성 int link(const char *oldpath, const char *newpath);
심벌릭 링크 생성 int symlink(const char *target, const char *linkpath);
심벌릭 링크 정보 검색 int lstat(const char *pathname, struct stat *statbof);
심벌릭 링크 내용 읽기 ssize_t readlink(const char *pathname, char *buf, size_t bufsiz);
심벌릭 링크 원본 파일의 경로 검색 char *realpath(const char *path *resolved_path);
링크 끊기 int unlink(const char *pathname);

 

 

 

  파일 정보 검색

  inode의 정보를 검색하려면 stat(), lstat(), fstat() 함수를 사용한다.

 

  파일명으로 파일 정보 검색 : stat()

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

int stat(const char *pathname, struct stat *statbuf);

    pathname : 정보를 알고자 하는 파일명,  statbuf : 검색한 파일 정보를 저장할 구조체 주소

 

 

 

  stat 구조체

 

struct stat{
    dev_t			st_dev;
    ino_t			st_ino;
    mode_t			st_mode;
    nlink_t			st_nlink;
    uid_t			st_uid;
    gid_t			st_gid;
    dev_t			st_rdev;
    off_t			st_size;
    blksize_t			st_blksize;
    blkcnt_t			st_block;
    struct timespec		st_atim;
    struct timespec		st_mtim;
    struct timespec		st_ctim;
    
    #define struct timespec	st_atim.tv_sec
    #define struct timespec	st_atim.tv_sec
    #define struct timespec	st_atim.tv_sec
}

 

  - st_dev : 파일이 저장되어 있는 장치의 번호를 저장

  - st_ino : 파일의 inode 번호를 저장

  - st_mode : 파일의 종류와 접근 권한을 저장

  - st_nlink : 하드 링크의 개수를 저장

  - st_uid : 파일 소유자의 UID를 저장

  - st_gid : 파일 소유 그룹의 GID를 저장

  - st_rdev : 장차 파일이면 주 장치 번호와 부 장치 번호를 저장

  - st_blksize : 파일 내용을 입출력할 때 사용하는 버퍼의 크기 저장

  - st_blocks : 파일에 할당된 파일 시스템의 블록 수로, 블록의 크기는 512바이트이다

 

 

  timespec 구조체

struct timespec{
    __kernel_time_t	tv_sec;		/* 초 (seconds) */
    long		tv_nsec;	/* 나노초 (nanoseconds) */
};

 

  - st_atime : 마지막으로 파일을 읽거나 실행한 시각을 timespec 구조체로 저장 (1970년 1월 1일 이후 시각으로 가능)

  - st_atime : 마지막으로 파일의 내용을 변경한 시각을 timespec 구조체로 저장

  - st_atime : 마지막으로 inode의 내용을 변경할 시각을 저장

 

 

 

  파일명으로 inode 정보 검색하기 : stat()

 

 

 

  파일 기술자로 파일 정보 검색하기 : fstat()

 

  fstat() 함수는 파일 경로 대신 현재 열려있는 파일의 파일 기술자를 인자로 받아 파일 정보를 검색한 후,

 statbuf로 지정한 구조체에 저장한다.

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

int stat(const char *pathname, struct stat *statbuf);