load an unknown named .txt file c++

here is what i currently have

1
2
3
4
5
6
7
8
9
10
11
12
13
14
  ifstream Myfile("tests000.txt");
int trow=0;
    int trow0=0,  trow1=0,      trow2=0,      trow3=0,      trow4=0,      trow5=0,      trow6=1;
                int tcol;
            if(Myfile.is_open())    //opens dictionary
                {
             while(!Myfile.eof())
                {

getline(Myfile, lines);

................etc.




however i need to load files that are all going to be named test00*.txt so like test001, test002, test003. how would i change this to make it load the present one in the same dir, and not just the test000.txt? thanks
You will need an 'itoa()' function of some sort:

1
2
3
4
5
for (int iFile = 0; iFile < FILE_COUNT; iFile++) {
    string sFilename = string("tests00") + itoa(iFile) + ".txt";
    ifstream Myfile(sFilename.c_str());
    ...
}


It can also be done with a stringstream:
1
2
3
4
5
6
for (int iFile = 0; iFile < FILE_COUNT; iFile++) {
    stringstream ssFilename;
    ssFilename << "tests00" << iFile << ".txt";
    ifstream Myfile(sFilename.str().c_str());
    ...
}
Last edited on
If you know the amount of files there are going to be you could do something like.

1
2
3
4
5
6
7
8
9
int numberOfFiles = 10;
for(int i = 0; i < numberOfFiles; i++)
{
	char fileName[128];
	sprintf(fileName, "test00%d.txt", i );
	
        ifstream MyFile(fileName);
        /* use the file ... */
}


I've never used these ones myself but you might find some use out of:
http://msdn.microsoft.com/en-us/library/aa364418(VS.85).aspx
http://msdn.microsoft.com/en-us/library/aa364428(VS.85).aspx

I'm sure theres a function somewhere that could scan a directory for the number of files containing ".txt" in them. Have a google around.
Topic archived. No new replies allowed.