0

Hi all. I've written a bit of code to open a file and read from it. The simple version works:

ifstream conFile("code/constants.h", ios::in);

	while (getline(conFile, line))
	{
          //etc.  Process file..........

However, I really want the program to look for the file constants.h in the current directory and if it doesn't find it, look in a directory called "code". The following code doesn't produce the error message saying the file wasn't opened, but doesn't read and process the file either. Am I not seeing a really obvious error? Thanks for the help!

ifstream conFile;

	conFile.open("constants.h", ios::in);
	
       if (!conFile.is_open()) 
	conFile.open("code/constants.h", ios::in);

	if (!conFile.is_open()) 		
	{	cout << "Unable to open constants.h for file header information. \n";
	        exit(0);
	}

       else {
	     while (getline(conFile, line))
	     {
                   //etc.  Process file..........
2
Contributors
2
Replies
3
Views
9 Years
Discussion Span
Last Post by kimn
0

You might need to clear any set flags before you try to use the same file pointer "conFile" to access the second file.

ie

if (!conFile){
        conFile.clear(); 
	conFile.open("code/constants.h", ios::in);
}
0

You are an angel! Thank you, that fixed it!

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.