如何使用 C 或 C++ 获取目录中的文件列表?我的程序不允许使用 ls
这样的命令。
Linux 平台
可以使用 opendir,如下,
char dirname[] = "/usr/local"
DIR *dir_ptr;
struct dirent *direntp;
dir_ptr = opendir(dirname);
if (dir_ptr == NULL)
fprintf(stderr,"Ls: can not open %s",dirname);
else
{
direntp = readdir(dir_ptr);
while(direntp == NULL)
printf("%s\n",direntp->d_name);
closedir(dir_ptr);
}
Windows 平台
#include <windows.h>
#include <tchar.h>
#include <stdio.h>
void _tmain(int argc, TCHAR *argv[])
{
WIN32_FIND_DATA FindFileData;
HANDLE hFind;
if (argc != 2)
{
_tprintf(TEXT("Usage: %s [target_file]\n"), argv[0]);
return;
}
_tprintf (TEXT("Target file is %s\n"), argv[1]);
hFind = FindFirstFile(argv[1], &FindFileData);
if (hFind == INVALID_HANDLE_VALUE)
{
printf ("FindFirstFile failed (%d)\n", GetLastError());
return;
}
else
{
_tprintf (TEXT("The first file found is %s\n"), FindFileData.cFileName);
FindClose(hFind);
}
}
跨平台下 C++17
#include <string>
#include <iostream>
#include <filesystem>
namespace 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;
}