如何在c++中从一个目录一个接一个地调用txt文件
how to call txt files from a directory one by one in c++
我知道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();
}
我该怎么做?
处理目录不是C++标准库的一部分。您可以使用依赖于平台的API(例如POSIX上的dirent.h
)或它们周围的包装器,例如boost::filesystem
。
如果像我在这里那样使用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 directoryn";
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 searchingn";
}
system("pause");
return 0;
}
`
相关文章:
- 基于另一个成员参数将函数调用从类传递给它的一个成员
- 构造函数正在调用一个使用当前类类型的函数
- 我不小心调用了一个没有自己类对象的成员函数.但这是怎么回事呢
- 在另一个线程中调用luaL_error会引发qWarning
- 如何在qt中从另一个类调用函数
- 检查哪个对象调用了另一个对象的对象方法
- GLEW/GLUT:调用init并创建一个窗口后,取消初始化并重新初始化?
- 我有一个调用ID3D11DeviceContext::CopySubresourceRegion的循环.我怎么能强制等待
- 当另一个调用 lambda 使用默认捕获时,lambda 的闭包可能会被破坏吗?
- 在C++中嵌入Python:在Python脚本中导入模块在一个函数调用过程中有效,但在另一个调用过程中无效
- 如何在一个调用中释放多个互斥对象
- 我希望计时器只在上一个调用返回或完成执行时调用代码
- 定义一个调用其他函数的内联函数是否有意义
- 我如何测试一个调用是在谷歌测试延迟后使用嘲讽框架进行的
- 我想创建一个调用函数的源文件,而不必创建对象
- 是否有可能制作一个调用jdbc的Java JNI
- 如果您有一个调用其他内部函数的类接口函数
- 打开文件来自一个调用请求在黑莓10级联
- 创建一个调用另一个可执行文件的可执行文件
- 什么是崩溃我的应用程序的异常,给定一个调用堆栈与UnhandledExceptionFilter