如何在c++中从一个目录一个接一个地调用txt文件

how to call txt files from a directory one by one in c++

本文关键字:一个 调用 txt 文件 c++      更新时间:2023-10-16

我知道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;
    }
`