open() method not working for multiple files.

Hello all,

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)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
  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?

Thanks.
You need to .clear() the stream after you get to the end of it (or you get an error).
Awesome, that does the trick.

Thanks Firedraco!
Topic archived. No new replies allowed.