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..........

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

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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.