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

리눅스 시스템에서는 디렉토리 파일을 열어 디렉토리 엔트리 목록을 읽고 탐색할 수 있는 시스템 호출을 제공하고 있어요.

디렉토리 파일을 열 때는 opendir, 디렉토리 엔트리를 읽을 때는 readdir, 디렉토리 파일의 시작 위치로 이동할 때는 rewinddir, 디렉토리 파일을 닫을 때는 closedir 함수를 사용합니다.

#include <sys.types.h >

#include <dirent.h>

DIR *opendir(const char *pathname);

반환 값: 실패 시 NULL

struct dirent *readdir(DIR *dir);

반환 값: 실패 시 NULL

void rewinddir(DIR *dir);

int closedir(DIR *dir);

반환 값: 실패 시 -1, 성공 시 0

다음은 main함수 인자로 전달받은 디렉토리 파일을 열어 디렉토리 엔트리를 출력하는 예제 코드입니다.

/**********************************************************************
* ex_dirent.c                                                         *
* exmple source – about dirent type                                   *
**********************************************************************/

#include <sys/stat.h>
#include <dirent.h>
#include <stdio.h>

int main(int argc, char **argv)
{
    if(argc != 2)
    {
        fprintf(stderr, "Usage: %s <path name>\n", argv[0]);
        return 1;
    }

    DIR *dir = opendir(argv[1]);
    if(dir == NULL)
    {
        printf("failed open\n");
        return 1;
    }

    struct dirent *de=NULL;

    while((de = readdir(dir))!=NULL)
    {
        printf("%s %ld\n",de->d_name, de->d_ino);
    }
    closedir(dir);

    return 0;
}
[그림 6.2] ex_dirent 실행 화면
[그림 6.2] ex_dirent 실행 화면

리눅스 시스템 프로그래밍