Search code examples
c++file-ioifstream

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


I know the number of files in my \data directory (n). I want to do something like that:

#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();
}   

How can I do that?


Solution

  • If you use a do-while like I did here, you find the first file with FindFirstFile then read through them until you run out of .txt files. I'm not sure that do-while is necessarily the most effective method however.

        #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;
        }
    `