I have a program where I want to point the same ifstream to another file when I am done using it.

Currently, I have it set up something like this (pseudocode):

//Global File Name
char *mmFileName[50]

void calculateISI()
{
ifstream minmaxFS;
//sets the global file name
if(condition)
setGlobalFileName();
while(//assume true)
{
if(condition)
{
if(minmaxFS.is_open())
{
minmaxFS.clear();
minmaxFS.close();
}
cout << "Opening new file..." << endl;
minmaxFS.open(mmFileName);
if(minmaxFS.good())
cout << "Open success!" << endl;
else
cout << "Open Fail!" << endl;
}
minmaxFS >> temp;
//condition checking here
}
}

Problem is, I can never open the file successfully. The first run will open the file just fine (condition is set true, then after opening is set false). Then, when I try to open another file with the same fstream, it fails to read anything from the new file. I am sure the rest of my code is correct, it's only the closing current fstream/opening a new one that I am unsure about.

Any help is greatly appreciated!

Edited 3 Years Ago by happygeek: fixed formatting

Sorry, I hit "enter" and prematurely posted. Edited!

I hate it when I do that :cheesy:


try moving the clear line after closing the file. This works ok.

int main()
{
	string line;
	ifstream in("myfile1.txt");
	if(in.is_open())
	{
		while(!in.eof())
		{
			getline(in,line);
			cout << line << endl;
		}
		in.close();
		in.clear();
	}

	in.open("myfile2.txt");
	if(in.is_open())
	{
		while(!in.eof())
		{
			getline(in,line);
			cout << line << endl;
		}
		in.close();
		in.clear();
	}
	return 0;
}
This article has been dead for over six months. Start a new discussion instead.