C++: How do you pass a file as an argument?

17,085

Solution 1

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
}

Solution 2

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.

Share:
17,085
Shadi
Author by

Shadi

Updated on June 04, 2022

Comments

  • Shadi
    Shadi about 2 years

    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 declared above - how???
    }