C & LINUX

C / LINUX stat() fstat() lstat()

Ocean_ 2022. 5. 1. 18:33

함수 기능

pathname/fildes파일의 stat구조체를 리턴하는 시스템호출

stat

지정한 pathname에 해당하는 파일에 대한 정보를 넣은 stat구조체를 buf로 리턴

fstat

지정 filedes 오픈 확인하고 해당파일에 대한 정보를 넣은 stat구조체를 buf로 리턴

lstat

심볼릭 링크 파일 자체에 대한 정보를 넣은 stat구조체 자체 리턴

함수 원형

#include<sys/stat.h>
#include<sys/types.h>
#include<unistd.h>
int stat(const char *restrict pathname, struct stat *restrict buf)
int fstat(int filedes, struct stat *buf)
int lstat(const char *restrict pathname, struct stat *restrict buf)

리턴 값 : Pathname,filedes 파일의 stat 구조체 리턴하는 시스템호출

함수 파라메터

pathname

파일이름

 

filedes

파일 디스크립터

 

buf

stat구조체 리턴받을 버퍼

함수 예제

stat1

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

int main(int argc, char*argv[]){
    struct stat statbuf;

    if(argc!=2){
        fprintf(stderr, "usage: %s <file>\n",argv[0]);
        exit(1);
    }

    if((stat(argv[1], &statbuf))<0){
        fprintf(stderr,"stat error\n");
        exit(1);
    }

    printf("%s is %ld bytes\n", argv[1],statbuf.st_size);
    exit(0);
}

stat2

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

struct stat statbuf;

void ssu_checkfile(char *fname, time_t *time);

int main(int argc, char *argv[]){
    time_t intertime;

    if(argc !=2){
        fprintf(stderr, "usage: %s <file>\n",argv[0]);
        exit(1);
    }

    if(stat(argv[1],&statbuf)<0){
        fprintf(stderr, "stat error for %s\n",argv[1]);
        exit(1);
    }
    
    intertime = statbuf.st_mtime;
    while(1){
        ssu_checkfile(argv[1], &intertime);
        sleep(10);
    }
}

void ssu_checkfile(char *fname, time_t *time){
    if(stat(fname, &statbuf)<0){
        fprintf(stderr, "Warning : ssu_checkfile() error!\n");
        exit(1);
    }
    else
        if(statbuf.st_mtime != *time){
            printf("Warning : %s was modified!.\n",fname);
            *time = statbuf.st_mtime;
        }
}

함수 결과

stat1

stat2

 

 

리눅스시스템 프로그래밍 - 홍지만 저

교재 내에 있는 예제를 바탕으로 작성한 글 입니다.