seperate functions that open/close files

Hi, I have a quick question. I need to make two seperate functions that open and close a file. Normally I would make something that looks like this:

1
2
3
4
5
6
7
8
9
10
11
 std::fstream myfiles;
void exampleFunction(std::string filename){
  myfiles.open(filename, std::ios_base::in | std::ios_base::out);
  if(!myfiles.is_open()){
    //do stuff here
   }
  else 
   //do stuff here
  myfiles.close()
  return;
}


so here's the question. If i make a simple funtion that does simply:
1
2
3
4
5
void openfiles(std::string filename){
  myfiles.open(filename, std::ios_base::in | std::ios_base::out);
  //do stuff
  return;
}


and for the closing function:
1
2
3
void closeFile(){
  myfiles.close();
}

Would this be okay? Would there be any loss of data or anything?
Sure, but you can do better by not relying on global variables.
1
2
3
4
5
6
7
8
9
void openfiles(std::string filename, std::fstream &myfiles){
  myfiles.open(filename, std::ios_base::in | std::ios_base::out);
  //do stuff
  return;
}

void closeFile(std::fstream &myfiles){
  myfiles.close();
}
That will work, but I recommend that you don't do that.

First, global variables should be avoided if possible, as they make it harder to understand the flow of data through the program.
Second, C++ encourages the use of RAII for resource management whenever possible. When RAII is used to its full effect, most the lifetime of objects become tied to the program structure. For example, for a file, one might do this:
1
2
3
4
5
6
{
    std::fstream file(/*parameters*/); //If you pass parameters to the constructor, it will open the file for you.
    //Now file is open.
    //Use the file normally.
    //Don't call close().
}   //When the object goes out of scope, the file is closed automatically. 
This style minimizes programmer errors, because at any point that you can reference the 'file' object you know that the file is open and ready for use. Compare:
1
2
3
4
5
6
//'file' declared outside the scope.
{
    file.read(/*...*/); //Will this work? Is the file open now?
    some_random_function(); //Does this function call open() or close()?
    file.write(/*...*/); //Is the file still open? Are we even writing to the same file?
}

Try to structure your code so that a) you never explicitly call open() or close() on file streams, and b) pass the std::fstream object to the functions that need it, rather than declaring it in global scope.
right, i should've said that this is all within a class that i made. I have fstream as a private member variable. That being said, would that be okay if this is all within the class still?
In that case, opening in the constructor is acceptable. Since the file is a class member, you can omit the call to close(), since the destructor will do that anyway.
awesome, thank you!
Topic archived. No new replies allowed.