The c++ way of working with files is through file stream objects. There are 3 types of file streams, according to the operation you are to perform on it. There is std::ifstream for input operations, std::ofstream for output operations and std::fstream which allows both acess types. If you start using these objects then you can pass the object as a reference to any function where you intend to use it. For instance:
Code:
#include <fstream>
void somefn(const std::fstream& myfile) // notice the function takes a reference (notice the &)
{
// perform some I/O on the file
}
int main()
{
std::fstream myfile("somefile.txt", std::ios::out | std::ios::trunc); // set flags defining open mode, in this case output + truncate mode
// check if file was open
if (!myfile.is_open) {
std::cout << "unable to open file. quitting." << std::endl;
exit(1);
}
somefn(myfile);
}
Using file streams is quite nice as it simplifies a lot some file i/o operations. writting and reading operations, since it is a stream it allows you to use the some of the methods you use with regular streams.
cheers