如何从我的C或c++代码中确定目录中的文件列表?
我不允许在程序中执行ls命令并解析结果。
如何从我的C或c++代码中确定目录中的文件列表?
我不允许在程序中执行ls命令并解析结果。
当前回答
试试来自direct .h的scandir()
男人scandir ()
其他回答
一个函数就足够了,你不需要使用任何第三方库(对于Windows)。
#include <Windows.h>
vector<string> get_all_files_names_within_folder(string folder)
{
vector<string> names;
string search_path = folder + "/*.*";
WIN32_FIND_DATA fd;
HANDLE hFind = ::FindFirstFile(search_path.c_str(), &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;
}
PS:正如@Sebastian提到的,你可以改变*。*到*。ext,以便只获得该目录中的ext文件(即特定类型的文件)。
看看这个使用win32 api的类。只需要构造一个实例,提供您想要清单的文件夹名,然后调用getNextFile方法从目录中获取下一个文件名。我认为它需要windows.h和stdio.h。
class FileGetter{
WIN32_FIND_DATAA found;
HANDLE hfind;
char folderstar[255];
int chk;
public:
FileGetter(char* folder){
sprintf(folderstar,"%s\\*.*",folder);
hfind = FindFirstFileA(folderstar,&found);
//skip .
FindNextFileA(hfind,&found);
}
int getNextFile(char* fname){
//skips .. when called for the first time
chk=FindNextFileA(hfind,&found);
if (chk)
strcpy(fname, found.cFileName);
return chk;
}
};
2017年更新:
在c++ 17中,现在有一种官方的方法来列出文件系统中的文件:std::filesystem。下面是Shreevardhan给出的一个很好的答案:
# include <字符串> # include < iostream > # include <文件> 命名空间fs = std::filesystem; int main () { Std::string path = "/path/to/directory"; For (const auto & entry: fs::directory_iterator(path)) Std::cout << entry.path() << Std::endl; }
旧的回答:
在小而简单的任务中,我不使用boost,我使用direct .h。它可以作为UNIX中的标准标头使用,也可以通过Toni Ronkko创建的兼容层用于Windows。
DIR *dir;
struct dirent *ent;
if ((dir = opendir ("c:\\src\\")) != NULL) {
/* print all the files and directories within directory */
while ((ent = readdir (dir)) != NULL) {
printf ("%s\n", ent->d_name);
}
closedir (dir);
} else {
/* could not open directory */
perror ("");
return EXIT_FAILURE;
}
它只是一个小的头文件,做了大部分你需要的简单的事情,而不使用像boost这样的基于模板的大方法(无意冒犯,我喜欢boost!)
char **getKeys(char *data_dir, char* tablename, int *num_keys)
{
char** arr = malloc(MAX_RECORDS_PER_TABLE*sizeof(char*));
int i = 0;
for (;i < MAX_RECORDS_PER_TABLE; i++)
arr[i] = malloc( (MAX_KEY_LEN+1) * sizeof(char) );
char *buf = (char *)malloc( (MAX_KEY_LEN+1)*sizeof(char) );
snprintf(buf, MAX_KEY_LEN+1, "%s/%s", data_dir, tablename);
DIR* tableDir = opendir(buf);
struct dirent* getInfo;
readdir(tableDir); // ignore '.'
readdir(tableDir); // ignore '..'
i = 0;
while(1)
{
getInfo = readdir(tableDir);
if (getInfo == 0)
break;
strcpy(arr[i++], getInfo->d_name);
}
*(num_keys) = i;
return arr;
}
GNU手册FTW
http://www.gnu.org/software/libc/manual/html_node/Simple-Directory-Lister.html#Simple-Directory-Lister
此外,有时直接找到源头是件好事(双关)。通过查看Linux中一些最常见命令的内部结构,您可以学到很多东西。我在github上建立了一个GNU coreutils的简单镜像(供阅读)。
https://github.com/homer6/gnu_coreutils/blob/master/src/ls.c
也许这并不能解决Windows的问题,但是通过使用这些方法,可以实现使用Unix变体的许多情况。
希望这对你有所帮助……