I am using ifstream to open a file. I have a loop that opens and reads from all of the files (.txt) in a directory. It reads the contents then closes the file and opens the next file. (BTW I know that gotos are frowned upon but I use it here to shorten the example)
string filenameRead;
ifstream infile;
string listfileName ="list.lst";
/* open the listing file, contains list of all .txt files in directory */
listfile.open(listfileName.c_str());
nextfile:
/* Get name of txt file to open */
while(std::getline(listfile, filenameRead)) {
/* Open the file */
infile.open(pathToFile.c_str());
/* did file open? */
if (infile.fail())
goto nextfile;
/* Process file.....*/
/* close the file */
infile.close()
goto nextfile;
}
Now this works great for the first file in the list, however in subsequent files the infile.fail() returns true. It ONLY works if I move ifstream infile; into the while loop essentially recreating the file stream for each new file. Any ideas on why this works this way?