C_C++

(C언어) 지정된 폴더의 파일 목록 출력하기

고니자니 2023. 7. 10. 12:02
반응형

다음 코드는 윈도우에서 지정한 폴더(디렉토리)의 파일과 하위 폴더의 파일 목록을 출력하는 C언어 소스입니다.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <io.h>
#include <Windows.h>
#pragma warning ( disable : 4996 )

#define DIRECTORY 1
#define FILE 0

struct _finddata_t fd;

int isDirectory()
{
    if (fd.attrib & _A_SUBDIR)
        return DIRECTORY; 
    else
        return FILE; 

}

void FileSearch(char path[])
{
    intptr_t handle;
    int check = 0;
    char path2[_MAX_PATH];

    strcpy(path2, path);
    strcat(path, "\\");
    strcat(path, "*.*");

    if ((handle = _findfirst(path, &fd)) == -1)
    {
        //printf("%s - No such file or directory\n",path);
        return;
    }

    while (_findnext(handle, &fd) == 0)
    {
        char file_pt[_MAX_PATH];
        strcpy(file_pt, path2);
        strcat(file_pt, fd.name);

        check = isDirectory();    // 디렉토리 판별

        if (isDirectory() && fd.name[0] != '.')  //<.>, <..>이 아닌 디렉토리 
        {
            strcat(file_pt, "\\");
            FileSearch(file_pt);    // 하위 디렉토리 검색
        }
        else if (check == FILE && fd.size != 0 && fd.name[0] != '.')
        {
            printf("%s, %d 바이트\n", file_pt, fd.size);
        }
    }
    _findclose(handle);
}

int main()
{
    char dir[_MAX_PATH] = "c:\\temp\\";

    FileSearch(dir);

    return 0;
}

지정된 폴더의 파일 목록 출력하기

 

728x90
반응형