如何獲取目錄中的文件列表,以便可以處理每個文件?如何獲取C++目錄中的文件列表?
43
A
回答
34
標準C++沒有提供這樣做的方法。但boost::filesystem
能做到這一點:http://www.boost.org/doc/libs/1_37_0/libs/filesystem/example/simple_ls.cpp
2
解決這將需要一個平臺,具體的解決方案。在Windows上查找unix/linux或FindFirstFile()上的opendir()。或者,有許多庫可以爲您處理特定於平臺的部分。
25
這是Linux上C語言的一個例子。如果,你是在Linux上,不介意在ANSI C.
#include <dirent.h>
DIR *dpdf;
struct dirent *epdf;
dpdf = opendir("./");
if (dpdf != NULL){
while (epdf = readdir(dpdf)){
printf("Filename: %s",epdf->d_name);
// std::cout << epdf->d_name << std::endl;
}
}
closedir(dpdf);
2
這樣小一點。如果你在Windows &是使用MSVC的,MSDN庫具有sample code that does this.
而這裏的從該鏈接代碼:
#include <windows.h>
#include <tchar.h>
#include <stdio.h>
#include <strsafe.h>
void ErrorHandler(LPTSTR lpszFunction);
int _tmain(int argc, TCHAR *argv[])
{
WIN32_FIND_DATA ffd;
LARGE_INTEGER filesize;
TCHAR szDir[MAX_PATH];
size_t length_of_arg;
HANDLE hFind = INVALID_HANDLE_VALUE;
DWORD dwError=0;
// If the directory is not specified as a command-line argument,
// print usage.
if(argc != 2)
{
_tprintf(TEXT("\nUsage: %s <directory name>\n"), argv[0]);
return (-1);
}
// Check that the input path plus 2 is not longer than MAX_PATH.
StringCchLength(argv[1], MAX_PATH, &length_of_arg);
if (length_of_arg > (MAX_PATH - 2))
{
_tprintf(TEXT("\nDirectory path is too long.\n"));
return (-1);
}
_tprintf(TEXT("\nTarget directory is %s\n\n"), argv[1]);
// Prepare string for use with FindFile functions. First, copy the
// string to a buffer, then append '\*' to the directory name.
StringCchCopy(szDir, MAX_PATH, argv[1]);
StringCchCat(szDir, MAX_PATH, TEXT("\\*"));
// Find the first file in the directory.
hFind = FindFirstFile(szDir, &ffd);
if (INVALID_HANDLE_VALUE == hFind)
{
ErrorHandler(TEXT("FindFirstFile"));
return dwError;
}
// List all the files in the directory with some info about them.
do
{
if (ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
{
_tprintf(TEXT(" %s <DIR>\n"), ffd.cFileName);
}
else
{
filesize.LowPart = ffd.nFileSizeLow;
filesize.HighPart = ffd.nFileSizeHigh;
_tprintf(TEXT(" %s %ld bytes\n"), ffd.cFileName, filesize.QuadPart);
}
}
while (FindNextFile(hFind, &ffd) != 0);
dwError = GetLastError();
if (dwError != ERROR_NO_MORE_FILES)
{
ErrorHandler(TEXT("FindFirstFile"));
}
FindClose(hFind);
return dwError;
}
void ErrorHandler(LPTSTR lpszFunction)
{
// Retrieve the system error message for the last-error code
LPVOID lpMsgBuf;
LPVOID lpDisplayBuf;
DWORD dw = GetLastError();
FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
NULL,
dw,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPTSTR) &lpMsgBuf,
0, NULL);
// Display the error message and exit the process
lpDisplayBuf = (LPVOID)LocalAlloc(LMEM_ZEROINIT,
(lstrlen((LPCTSTR)lpMsgBuf)+lstrlen((LPCTSTR)lpszFunction)+40)*sizeof(TCHAR));
StringCchPrintf((LPTSTR)lpDisplayBuf,
LocalSize(lpDisplayBuf)/sizeof(TCHAR),
TEXT("%s failed with error %d: %s"),
lpszFunction, dw, lpMsgBuf);
MessageBox(NULL, (LPCTSTR)lpDisplayBuf, TEXT("Error"), MB_OK);
LocalFree(lpMsgBuf);
LocalFree(lpDisplayBuf);
}
4
你必須使用操作系統調用(如在Win32 API)或他們周圍的包裝。我傾向於使用Boost.Filesystem,因爲它與Win32 API(以及跨平臺)混亂相比,它是高級界面。
如果您正在尋找使用Win32 API,Microsoft在msdn上有一個列表of functions和examples。
56
下面是我用什麼:
/* Returns a list of files in a directory (except the ones that begin with a dot) */
void GetFilesInDirectory(std::vector<string> &out, const string &directory)
{
#ifdef WINDOWS
HANDLE dir;
WIN32_FIND_DATA file_data;
if ((dir = FindFirstFile((directory + "/*").c_str(), &file_data)) == INVALID_HANDLE_VALUE)
return; /* No files found */
do {
const string file_name = file_data.cFileName;
const string full_file_name = directory + "/" + file_name;
const bool is_directory = (file_data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0;
if (file_name[0] == '.')
continue;
if (is_directory)
continue;
out.push_back(full_file_name);
} while (FindNextFile(dir, &file_data));
FindClose(dir);
#else
DIR *dir;
class dirent *ent;
class stat st;
dir = opendir(directory);
while ((ent = readdir(dir)) != NULL) {
const string file_name = ent->d_name;
const string full_file_name = directory + "/" + file_name;
if (file_name[0] == '.')
continue;
if (stat(full_file_name.c_str(), &st) == -1)
continue;
const bool is_directory = (st.st_mode & S_IFDIR) != 0;
if (is_directory)
continue;
out.push_back(full_file_name);
}
closedir(dir);
#endif
} // GetFilesInDirectory
0
HANDLE WINAPI FindFirstFile(
__in LPCTSTR lpFileName,
__out LPWIN32_FIND_DATA lpFindFileData
);
設置屬性僅查找目錄。
0
或者你做到這一點,然後讀出的test.txt:
#include <windows.h>
int main() {
system("dir /b > test.txt");
}
的「/ B」指的只是文件名返回,沒有進一步的信息。
-1
void getFilesList(String filePath,String extension, vector<string> & returnFileName)
{
WIN32_FIND_DATA fileInfo;
HANDLE hFind;
String fullPath = filePath + extension;
hFind = FindFirstFile(fullPath.c_str(), &fileInfo);
if (hFind == INVALID_HANDLE_VALUE){return;}
else {
return FileName.push_back(filePath+fileInfo.cFileName);
while (FindNextFile(hFind, &fileInfo) != 0){
return FileName.push_back(filePath+fileInfo.cFileName);}
}
}
String optfileName ="";
String inputFolderPath ="";
String extension = "*.jpg*";
getFilesList(inputFolderPath,extension,filesPaths);
vector<string>::const_iterator it = filesPaths.begin();
while(it != filesPaths.end())
{
frame = imread(*it);//read file names
//doyourwork here (frame);
sprintf(buf, "%s/Out/%d.jpg", optfileName.c_str(),it->c_str());
imwrite(buf,frame);
it++;
}
0
您可以使用下面的代碼來獲取目錄中的所有文件。對Andreas Bonini答案進行一個簡單的修改以消除「。」的出現。和 「..」
2
我剛剛問過類似的question和這裏的基礎上回答我的解決方案榮獲(使用boost::filesystem
庫):
#include <string>
#include <iostream>
#include <boost/filesystem.hpp>
using namespace std;
using namespace boost::filesystem;
int main()
{
path p("D:/AnyFolder");
for (auto i = directory_iterator(p); i != directory_iterator(); i++)
{
if (!is_directory(i->path())) //we eliminate directories in a list
{
cout << i->path().filename().string() << endl;
}
else
continue;
}
}
輸出是這樣的:
file1.txt
file2.dat
1
合併了很多片段之後,我終於找到了一個不會帶來錯誤的地方,它會接受一個std :: string參數並且可以重用。
#include <atlstr.h>
void getFiles(CString directory) {
Console console;
HANDLE dir;
WIN32_FIND_DATA file_data;
CString file_name, full_file_name;
if ((dir = FindFirstFile((directory + "/*"), &file_data)) == INVALID_HANDLE_VALUE)
{
// Invalid directory
}
while (FindNextFile(dir, &file_data)) {
file_name = file_data.cFileName;
full_file_name = directory + file_name;
if (strcmp(file_data.cFileName, ".") != 0 && strcmp(file_data.cFileName, "..") != 0)
{
std::string fileName = full_file_name.GetString();
// Do stuff with fileName
}
}
}
要訪問的方法,只要致電:
getFiles("i:\\Folder1");
1
C++ 11/Linux的版本:
#include <dirent.h>
if (auto dir = opendir("some_dir/")) {
while (auto f = readdir(dir)) {
if (!f->d_name || f->d_name[0] == '.')
continue; // Skip everything that starts with a dot
printf("File: %s\n", f->d_name);
}
closedir(dir);
}
相關問題
- 1. 如何獲取JAR文件中目錄下的文件列表
- 2. C:如何獲取Windows目錄下的文件列表?
- 3. 如何從文檔目錄中獲取xml文件的列表
- 4. 如何在Python中獲取目錄中的文件名列表
- 5. 獲取C中的目錄列表
- 6. 如何在禁用目錄列表時獲取文件列表?
- 7. 如何獲取lua目錄中的文件列表?
- 8. 如何使用Perl獲取目錄中純文件的列表?
- 9. 如何獲取os x目錄中的文件列表?
- 10. 如何從打開目錄列表的目錄中獲取文件?
- 11. 如何在java中獲取目錄url的文件/目錄列表?
- 12. 獲取文件列表,無子目錄
- 13. WinRT - 獲取文件和目錄列表
- 14. 文件協議獲取目錄列表
- 15. 如何從linux內核目錄中獲取文件列表?
- 16. 如何_directly_從.JAR子目錄中獲取文件列表 - JAVA
- 17. 如何獲取網上文件夾的目錄列表?
- 18. 如何在C#中獲取目錄大小(目錄中的文件)?
- 19. 如何讀取文檔目錄中存在的文件列表
- 20. 如何從Web目錄獲取文件列表?
- 21. 如何從URL Android獲取目錄和文件列表?
- 22. 如何只使用c#獲取目錄中的文件名?
- 23. 如何獲取目錄列表或'無'?
- 24. 如何獲取文件的父目錄?
- 25. 獲取服務器上的目錄中的文件列表iPhone
- 26. 獲取帶有擴展名的目錄中的文件列表
- 27. 將文本追加到文件(從目錄列表中獲取)
- 28. 如何獲得文件列表目錄中的編程
- 29. 如何從目錄中獲取子文件夾中的文件
- 30. 獲取目錄中所有文件的列表
不要忘了`closedir(dpdf)`之後 – jsj 2015-08-07 02:25:12
如何在這種情況下,我可以得到一個文件(FILE類型)嗎? epdf是「dirent *」 – 2016-04-05 11:05:34
如果您正在創建一個lib,則不能使用dirent。 – Katianie 2016-05-25 22:36:35