C,C++ & Linux

C/C++ closedir(3)

KyooDong 2020. 5. 20. 16:48
728x90

closedir(3) 함수 기능

디렉토리를 닫는 함수

함수 원형

#include <dirent.h>
#include <sys/types.h>

int closedir(DIR *dp);

매개변수

dp

닫고자하는 디렉토리의 DIR 포인터

반환값

성공 시 0 리턴

에러 시 -1 리턴하고 errno 설정

예제

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

#ifdef PATH_MAX
static int pathmax = PATH_MAX;
#else
static int pathmax = 0;
#endif

#define MAX_PATH_GUESSED 1024

#ifndef LINE_MAX
#define LINE_MAX 2048
#endif

char *pathname;
char command[LINE_MAX],  grep_cmd[LINE_MAX];

int ssu_do_grep() {
    struct dirent *dirp;
    struct stat statbuf;
    char *ptr;
    DIR *dp;

	// pathname 파일의 정보를 읽어들임
    if (lstat(pathname, &statbuf) < 0) {
        fprintf(stderr, "lstat error for %s\n", pathname);
        return 0;
    }

	// pathname 파일이 디렉토리가 아니라면
    if ((S_IFMT & statbuf.st_mode) != S_IFDIR) {
		// 해당 파일에서 grep 명령을 실행
        sprintf(command, "%s %s", grep_cmd, pathname);
        printf("%s : \n", pathname);
        system(command);
        return 0;
    }

	// 디렉토리라면
    ptr = pathname + strlen(pathname);
    *ptr++ = '/';
    *ptr = '\0';

	// 디렉토리를 연다.
    if ((dp = opendir(pathname)) == NULL) {
        fprintf(stderr, "opendir error for %s\n", pathname);
        return 0;
    }

	// 디렉토리 내부 파일을 순회한다.
    while ((dirp = readdir(dp)) != NULL)
		// 자기 자신을 의미하는 .과 부모 디렉토리를 의미하는 ..은 탐색에서 제외한다.
        if (strcmp(dirp->d_name, ".") && strcmp(dirp->d_name, "..")) {
			// ptr에 파일명을 세팅한다
			// 이는 곧 pathname에 파일명을 이어 붙인것과 같다.
            strcpy(ptr, dirp->d_name);

			// 재귀적으로 grep을 호출한다.
			// 결국 디렉토리의 모든 서브 디렉토리를 싹 들어가서
			// 모든 파일에 대해 grep을 하게된다.
            if (ssu_do_grep() < 0)
                break;
        }
    
	// 원래대로 pathname을 돌려놓는다.
    ptr[-1] = 0;
	
	// 디렉토리를 닫는다.
    closedir(dp);
    return 0;
}

void ssu_make_grep(int argc, char *argv[]) {
	// grep 명령을 만드는 함수
    strcpy(grep_cmd, " grep");

    for (int i = 1; i < argc - 1; i++) {
        strcat(grep_cmd, " ");
        strcat(grep_cmd, argv[i]);
    }
}


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

    if (pathmax == 0) {
        if ((pathmax = pathconf("/", _PC_PATH_MAX)) < 0)
            pathmax = MAX_PATH_GUESSED;
        else
            pathmax++;
    }

    if ((pathname = (char *) malloc(pathmax + 1)) == NULL) {
        fprintf(stderr, "malloc error\n");
        exit(1);
    }

    strcpy(pathname, argv[argc - 1]);
    ssu_make_grep(argc, argv);
    ssu_do_grep();
    exit(0);
}

 

결과

 

 

 

 

 

 

 

 

 

 

 

리눅스시스템프로그래밍 저자 : 홍지만
https://book.naver.com/bookdb/book_detail.nhn?bid=14623672

책에 기술된 예제 프로그램입니다. 책 내부에는 훨씬 더 많은 자료가 있습니다. (개인적으로 좋았습니다.)