In our team project, a file is to be continually read from using a while loop, and whenever a certain word is encountered, another file is to be opened to read its content, do some other things and then proceed. Hence, the need to read from another file while the first file is still open for reading; because once the first is closed then there is no way of continuing to read from where the reading stopped because the while loop terminates.
So, our problem now is creating independent ifstream objects for the files to be read from so that no need of closing one before another can be opened.
Please can someone help me with the code and syntax to follow in order to open a second file without closing the first.
Simple... there is no problem with opening two files at once. Just call an external method (or recursively call the same method) to read the second file. For example (using pseudo code since i am more familiar with non standard file classes such as those in Qt)
You may open as many files as your system and configuration will allow. Not sure what the max would be.
In my recent experience I have a program that has 3 open files to read and 1 file open for output. Another program open and closed different output files as it loops through the code. Each file that is opened creates a simple html file that is replaced by an updated html file later.
At the beginning of main or the function that would open the files your code would be,
1 2
ifstream InFile1;
ifstream InFile2;
where InFile1 and 2 would be whatever file name you would need. After that just open each file with a separate open statement for each. Sounds like you have the code to open 1 file already, just copy it and change the file names.
Unless you would need it earlier, just close each file before the program ends. You can close any of the files at any time you are done with them.
@DTM256
Thank you for providing another option if closing the file is necessary (the function he uses to get the file position depends on which class he is using to read it).
@nawas
Just keep in mind that closing the file is NOT necessary unless another application needs to "lock" it. It is perfectly fine to have multiple files open.