简体   繁体   English

C++:如何将文件作为参数传递?

[英]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.我在其中一个函数中初始化并打开了一个文件,我应该将 output 数据放入 output 文件中。 How can I pass the file as an argument so that I can output the data into the same output file using another function?如何将文件作为参数传递,以便可以使用另一个 output 将数据放入同一个 output 文件中,使用另一个 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,您的第二个 function 需要引用 stream 作为参数,即

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:传递对 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.如果您需要在 header 中声明second个并且不希望包含该 header 的文件被不必要的定义污染,您可以#include <iosfwd>获取istreamostream的前向声明。

The objects must be passed by non- const reference because insertion (for output streams) and extraction (input) modify the stream object.对象必须通过非const引用传递,因为插入(对于 output 流)和提取(输入)会修改 stream object。

Pass a reference to the stream.传递对 stream 的引用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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