Load list of files in directory without 'ls'

Asked 1 years ago, Updated 1 years ago, 106 views

I'd like to get a list of files in the directory from C/C++ ls I need something other than how to write command

c file c++ directory

2022-09-22 22:35

1 Answers

Different platforms write differently

DIR *dir;
struct dirent *ent;
char* src = "c:\\file path ..."
If ((dir = openir (src))! = NULL) { /* If the directory can be opened */
  /* Output all files & directories in the directory */
  while ((ent = readdir (dir)) != NULL) {
    printf ("%s\n", ent->d_name);
  }
  closedir (dir);
} else { /* If directory cannot be opened */
  perror ("");
  return EXIT_FAILURE;
}
#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;
}


2022-09-22 22:35

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.