[태그:] <span>S_ISDIR</span>

리눅스 시스템에서는 파일을 정규 파일, 디렉토리 파일, 블록 파일, 문자 파일, FIFO 파일, 기타 파일 등으로 구분합니다.

블록 파일과 문자 파일은 장치와 대응하는 파일로 블록 파일은 메모리 장치와 대응하고 문자 파일은 터미널 장치와 대응합니다. FIFO 파일은 프로세스와 프로세스 간의 통신에 사용하는 파일이며 이 외에도 링크 파일이나 소켓 등이 있습니다.

그리고 리눅스 시스템에서는 파일의 종류를 확인하는 매크로 함수들을 제공하고 있습니다.

#include <sys/stat.h >

S_ISREG – 정규 파일인지 판별

S_ISDIR – 디렉토리 파일인지 판별

S_ISCHR – 문자 장치 파일인지 판별

S_ISBLK – 블록 장치 파일인지 판별

S_ISFIFO – FIFO 파일인지 판별

다음은 stat 시스템 호출로 파일의 상태 값을 얻어온 후에 매크로 함수를 이용하여 파일의 종류를 출력하는 예제입니다.

/***********************************************************************
* ex_filetype.c                                                                     *
* example source - about file type                                          *
***********************************************************************/
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
const char *get_filetype(struct stat *buf);
int main(int argc,char **argv)
{    
    struct stat statbuf;
    
    if(argc != 2)
    {
        fprintf(stderr,"usage: %s <file name>\n",argv[0]);
        return 1;
    }
    if(stat(argv[1],&statbuf)<0)
    {
        perror("stat error");
        return 1;
    }
    printf("%s is %s file.\n",argv[1],get_filetype(&statbuf));
    return 0;
}
const char *get_filetype(struct stat *buf)
{
    if(S_ISREG(buf->st_mode))
    {
        return "regular";
    }
    if(S_ISDIR(buf->st_mode))
    {
        return "directory";
    }
    if(S_ISCHR(buf->st_mode))
    {
        return "charater";
    }
    if(S_ISBLK(buf->st_mode))
    {
        return "block";
    }
    if(S_ISFIFO(buf->st_mode))
    {
        return "fifo";
    }   
    return "unknown";
}
[그림 4.2] ex_filetype 실행 화면
[그림 4.2] ex_filetype 실행 화면

리눅스 시스템 프로그래밍