Global ifstream variable

Hi,

Please consider this following piece of code.
1
2
3
4
5
6
7
8
9
10
11
12
int main()
{
   ifstream objfile("log.txt");
   //
   for loop:
   process();
}

void process()
{
    // some processing
    // objfile.seekg(...)  //couldn't use objfile 


To use objfile in process() I thought of declaring it outside the main.

1
2
3
4
5
6
7
8

ifstream objfile

int main()
{
    objfile(somefileName); // gives error
}


error C2064: term does not evaluate to a function taking 1 arguments

Can you please suggest how to use objfile in process() function.
Functions can take parameters. Pass the ifstream variable to the function as a parameter.

1
2
3
void process(ifstream& some_stream)
{
  ...
Hi,

I would like to use objfile in several different functions. Rather than passing it as parameter across all those functions, is it possible to just declare it globally and use in different functions?
Rather than passing it as parameter across all those functions, is it possible to just declare it globally and use in different functions?

Yes it's possible. But you should strive to eliminate global variables whenever possible.

To use the global instance in this case you'll want to open() the file in main().
Last edited on
Topic archived. No new replies allowed.