我知道\data
目录(n)中的文件数。我想做那样的事情:
#include <string>
#include <fstream>
ifstream myFile;
string filename;
for(int i=0;i<n;i++)
{
filename=//call i'th file from the \data directory
myFile.open(filename);
//do stuff
myFile.close();
}
我该怎么做?
答案 0 :(得分:4)
处理目录不是C ++标准库的一部分。您可以使用平台相关的API(例如POSIX上的dirent.h
)或它们周围的包装器,例如: boost::filesystem
。
答案 1 :(得分:0)
如果您使用do-while
,就像我在此处所做的那样,您会找到带有FindFirstFile
的第一个文件,然后通读它们,直到您用完.txt文件为止。我不确定do-while
是否是最有效的方法。
#include <windows.h>
#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
using namespace std;
int main()
{
string path = "c:\\data\\";
string searchPattern = "*.txt";
string fullSearchPath = path + searchPattern;
WIN32_FIND_DATA FindData;
HANDLE hFind;
hFind = FindFirstFile( fullSearchPath.c_str(), &FindData );
if( hFind == INVALID_HANDLE_VALUE )
{
cout << "Error searching data directory\n";
return -1;
}
do
{
string filePath = path + FindData.cFileName;
ifstream in( filePath.c_str() );
if( in )
{
// do stuff
}
else
{
cout << "Problem opening file from data" << FindData.cFileName << "\n";
}
}
while( FindNextFile(hFind, &FindData) > 0 );
if( GetLastError() != ERROR_NO_MORE_FILES )
{
cout << "Something went wrong during searching\n";
}
system("pause");
return 0;
}
`