I initialized and opened a file in one of the functions and I am supposed to output data into an output file. How can I pass the file as an argument so that I can output the data into the same output file using another function? For example :
void fun_1 () {
ifstream in;
ofstream outfile;
in.open("input.txt");
out.open("output.txt");
////function operates////
//........
fun_2()
}
void fun_2 () {
///// I need to output data into the output file de开发者_JAVA百科clared above - how???
}
Your second function needs to take a reference to the stream as an argument, i.e.,
void fun_1 ()
{
ifstream in;
ofstream outfile;
in.open("input.txt");
out.open("output.txt");
fun_2( outfile );
}
void fun_2( ostream& stream )
{
// write to ostream
}
Pass a reference to the stream:
void first() {
std::ifstream in("in.txt");
std::ofstream out("out.txt");
second(in, out);
out.close();
in.close();
}
void second(std::istream& in, std::ostream& out) {
// Use in and out normally.
}
You can #include <iosfwd>
to obtain forward declarations for istream
and ostream
, if you need to declare second
in a header and don't want files that include that header to be polluted with unnecessary definitions.
The objects must be passed by non-const
reference because insertion (for output streams) and extraction (input) modify the stream object.
Pass a reference to the stream.
精彩评论