특정 디렉토리에 존재하는 파일의 총 개수를 알아내고 싶습니다.

jagalchee의 이미지

C 언어를 이용해서 특정 디렉토리에 존재하는 파일의 총 갯수를 알아내고 싶습니다. 어떻게 하면 될까요?

불량청년의 이미지

그냥 함수 몇개만 쓰시면 쉽게 찾을 수 있을꺼 같은데요.

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

int main(void)
{
    int    file_count = 0;
    char *dir_path = "/home/test/test_dir/";
    struct dirent *dir_ent;
    DIR  *dp;

    if ((dp = opendir(dir_path)) == NULL)
    {
        fprintf(stderr, "opendir() error!\n");
        exit(EXIT_FAILURE);
    }

    while ((dir_ent = readdir(dp)) != NULL)
    {
        if (strcmp(dir_ent->d_name, ".") == 0 || strcmp(dir_ent->d_name, "..") == 0)
            continue;

        ++file_count;
    }

    printf("File Count = %d\n", file_count);
    closedir(dp);
    exit(EXIT_SUCCESS);
}

간단하게 이정도면 될꺼 같네요.

H/W가 컴퓨터의 심장이라면 S/W는 컴퓨터의 영혼이다!

cdpark의 이미지

seekdir/telldir 함쑤 쌍을 쓸 수도 있을 듯 싶네요.