【问题标题】:C++: How do you pass a file as an argument?C++:如何将文件作为参数传递?
【发布时间】:2011-06-08 02:37:26
【问题描述】:

我在其中一个函数中初始化并打开了一个文件,我应该将数据输出到一个输出文件中。如何将文件作为参数传递,以便可以使用另一个函数将数据输出到同一个输出文件中?例如:

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

【问题讨论】:

    标签: c++ file arguments


    【解决方案1】:

    您的第二个函数需要将流的引用作为参数,即,

    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
    }
    

    【讨论】:

    • 我遇到了另一个问题,我有一个函数我必须 cin>> 一个整数,但它没有出现在输出文件中,为什么会这样,顺便感谢您的回复
    【解决方案2】:

    传递对流的引用:

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

    如果您需要在标头中声明 second 并且不希望包含该标头的文件被不必要的定义污染,您可以通过 #include <iosfwd> 获取 istreamostream 的前向声明。

    对象必须通过非const 引用传递,因为插入(用于输出流)和提取(输入)会修改流对象。

    【讨论】:

    • 我遇到了另一个问题,我有一个函数我必须 cin>> 一个整数,但它没有出现在输出文件中,为什么会这样,顺便感谢您的回复
    • @Shadi:所以你有类似int i; in >> i; out << i; 的东西?该文件在输出缓冲区被刷新之前不会被写入,所以你可以说out.close() 或使用out << std::flush 来确保你的数据被写入。
    • 不,实际上我有 cin>>i;出
    • @Shadi:这还不够信息。您应该提出一个新问题,并发布给您错误的代码。
    • 为什么我们传入打开的文件,但函数将文件的引用作为参数?为什么不是第二个(std::istream in, std::ostream out)?
    【解决方案3】:

    传递对流的引用。

    【讨论】:

      猜你喜欢
      • 2016-09-08
      • 1970-01-01
      • 1970-01-01
      • 2017-10-09
      • 1970-01-01
      • 2016-06-27
      • 1970-01-01
      • 1970-01-01
      • 2023-03-08
      相关资源
      最近更新 更多