0

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?

Werner Henze
  • 16,404
  • 12
  • 44
  • 69

2 Answers2

4

Handling directories is not part of the C++ standard library. You can use platform dependent APIs (e.g. dirent.h on POSIX) or a wrapper around them, e.g. boost::filesystem.

Markus Mayr
  • 4,038
  • 1
  • 20
  • 42
0

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;
    }
`
HavelTheGreat
  • 3,299
  • 2
  • 15
  • 34