C ++: How to pass a file as an argument?

I initialized and opened the file in one of the functions, and I have to output the data to the output file. How to pass a file as an argument so that I can output data to one output file using another function? For instance:

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 declared above - how???
}        
+3
source share
3 answers

The second function should take a stream reference 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
}
+4
source

Pass the link 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>get ads ahead for istreamand ostream, if you need to declare secondin the header and do not want the files containing this header to be contaminated with unnecessary definitions.

const, ( ) () .

+3

.

0

All Articles