简体   繁体   中英

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

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???
}        

Your second function needs to take a reference to the stream as an argument, ie,

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM