'ls'없이 디렉토리에 있는 파일 리스트 불러오기

조회수 4260회

C/C++에서 디렉토리에 있는 파일 리스트를 불러오고 싶어요 lscommand 쓰는 방법 말고 다른 게 필요해요

1 답변

  • 좋아요

    0

    싫어요
    채택 취소하기

    플랫폼에 따라 쓰는 방법이 다릅니다

    1. ###unix/linux - dirent.h

    DIR *dir;
    struct dirent *ent;
    char* src = "c:\\file path ..."
    if ((dir = opendir (src)) != NULL) { /* 디렉토리를 열 수 있는 경우 */
      /* 디렉토리 안에 있는 모든 파일&디렉토리 출력 */
      while ((ent = readdir (dir)) != NULL) {
        printf ("%s\n", ent->d_name);
      }
      closedir (dir);
    } else { /* 디렉토리를 열 수 없는 경우 */
      perror ("");
      return EXIT_FAILURE;
    }
    

    2. windows - Windows.h

    #include <Windows.h>
    
    vector<string> get_all_files_names_within_folder(string folder)
    {
        vector<string> names;
        char search_path[200];
        sprintf(search_path, "%s/*.*", folder.c_str());
        WIN32_FIND_DATA fd; 
        HANDLE hFind = ::FindFirstFile(search_path, &fd); 
        if(hFind != INVALID_HANDLE_VALUE) { 
            do { 
                // read all (real) files in current folder
                // , delete '!' read other 2 default folder . and ..
                if(! (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) ) {
                    names.push_back(fd.cFileName);
                }
            }while(::FindNextFile(hFind, &fd)); 
            ::FindClose(hFind); 
        } 
        return names;
    }
    

답변을 하려면 로그인이 필요합니다.

프로그래머스 커뮤니티는 개발자들을 위한 Q&A 서비스입니다. 로그인해야 답변을 작성하실 수 있습니다.

(ಠ_ಠ)
(ಠ‿ಠ)