reading data sequentially from text file

I would like to read data sequentially from a text file but I want to read different lines from the text file in different subroutines. Say I use code like

ifstream ReadFile("Filename.txt",ifstream::app);
ReadFile >> input_value_1
ReadFile >> input_value_2
etc.

in one routine, and then

ifstream ReadFile("Filename.txt",ifstream::app);
ReadFile >> input_value_3
ReadFile >> input_value_4
etc.

in a different routine. The call to ifstream in the second routine will put me back at the beginning of Filename.txt. That's not what I want. I want the read process to pick up where it left off in Filename.txt. Is there any way I can do this?

Thanks,

Paul.
Sure, just don't close and reopen the text file. An easy way to do this is to send your ifstream object into your routines as an argument or to just make it global.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
void routine1(ifstream& ReadFile)
{
  ReadFile >> input_value_1
           >> input_value_2;
}

void routine2(ifstream& ReadFile)
{
  ReadFile >> input_value_3
           >> input_value_4;
}

void masterFunction()
{
  ifstream ReadFile("Filename.txt",ifstream::app);
  routine1(ReadFile);
  routine2(ReadFile);
  ReadFile.close();
}
Last edited on
You would need to pass the filestream object as a parameter to the function to prevent the file from closing. You would then be able to read data from the top to bottom in this manner as well.

Another alternative is to return the file pointer (the object that indicates where the "cursor" is in the file) so that you can continue reading from the exact spot. This has the same effect as the previous option, but doesn't require the file to be open the entire time. You will, however, need to constantly open and close the file to grab your information.
closed account (o3hC5Di1)
Hi there,

What you could do is pass the ifstream as an argument to the different functions (subroutines).
That way it will be the same ifstream you're using, it also saves you from loading and unloading the file unnecessarily at every function call.

Rough Example:

1
2
3
4
5
6
7
8
9
10
11
int main()
{
    ifstream ifs;
    function_a(ifstream& ifs);
    return 0;
}

void function_a(ifstream& ifs)
{
   //do stuff with ifs here
}


Note that I'm passing the stream by reference.

Hope that helps, let me know if you need a more thorough explanation.

All the best,
NwN

Edit: Never mind - Stewbond and Volatile Pule beat me to it :)
Last edited on
Double Ninja'd.. Oh yeah
Seem to be making progress.

Thanks a lot for your help!

Paul
Topic archived. No new replies allowed.