【问题标题】:Keep a stream open from a function to another保持从一个函数到另一个函数的流打开
【发布时间】:2012-07-25 11:37:31
【问题描述】:

有没有办法让 C++ 中的流(读取或写入文件)从一个函数打开到另一个函数?

【问题讨论】:

  • 为什么需要这样做?您要解决的问题是什么?
  • 只需将其传递给函数而不关闭...如果这不能回答您的问题,请更具体。
  • 我开始认为可能有一个 fstream 对象在 in 函数中。
  • 我注意到流在作用域结束时自动关闭。现在我也只是尝试通过引用传递它,我在我的“文件”类的方法中使用它:int File::sendErrorOpeningStream(std::string ifstream_ofstream, std::ofstream outputFile, char *wd) 但是我想出了:error C2664:'File::sendErrorOpeningStream':无法转换参数 2从“std::ostream”到“std::ofstream”

标签: c++ file-io stream


【解决方案1】:

使其成为全局变量或将其作为参数传递,但请确保如果将其作为参数传递,则通过引用而不是通过值传递它!如果您按值传递它,编译器将不会抱怨并且奇怪的事情开始发生。

【讨论】:

  • 我很确定它会抱怨你不能复制它。除此之外,第二种选择要好得多。
  • @chris 我还没有看到编译器抱怨它,但你可能是对的。尽管如此,参考还是要走的路。
  • 我收到了Use of deleted function...。那是 C++11 特有的;不知道03年怎么样了。
【解决方案2】:

是的,您可以在函数之外创建流并将其作为参数传递给方法:

void myFunction(ifstream &stream) {...}

完成后关闭流:stream.close()

或者在第一个函数中创建流并将其返回给调用方法,然后将其传递给第二个函数。

【讨论】:

  • 在第一个函数中“创建”它会强制你创建堆,因为堆栈对象将超出范围。我不鼓励这样做。
  • 我在方法中使用它:int File::sendErrorOpeningStream (std::string ifstream_ofstream, std::ofstream outputFile, char *wd) 但然后我想出:error C2664: 'File::sendErrorOpeningStream' : cannot convert parameter 2 from 'std::ostream' to 'std::ofstream'
  • @RobinLen'hog:流不可复制。所以你不能按值传递它们。您必须通过引用传递。
  • 那我应该这样写吗? int File::sendErrorOpeningStream (std::string ifstream_ofstream, std::ofstream outputFile&, char *wd)??
【解决方案3】:

通过引用传递它

void myFunction(ifstream &myStream)

【讨论】:

    【解决方案4】:

    由于 C++11 文件流得到了move constructor (6)。您可以使用它在函数之间传递打开的流。考虑以下代码 sn-p:

    #include <iostream>
    #include <fstream>
    
    bool open_stream(const std::wstring& filepath, std::ifstream& stream)
    {
      std::ifstream innerStream;
      innerStream.open(filepath.c_str(), std::ios::in | std::ios::binary);
      if (innerStream.is_open())
      {
        stream = std::move(innerStream); // <-- Opened stream state moved to 'stream' variable 
        return true;
      }
      return false;
    }  // <-- innerStream is destructed, but opened stream state is preserved as it was moved to 'stream' variable
    

    考虑下一段代码来说明open_stream的用法:

    int main()
    {
      std::ifstream outerStream;
      std::wcout << L"outerStream is opened: " << outerStream.is_open() << std::endl; // <-- outerStream is opened: 0
    
      if (!open_stream(L"c:\\temp\\test_file.txt", outerStream))
      {
        return 1;
      }
    
      std::wcout << L"outerStream is opened: " << outerStream.is_open() << std::endl; // <-- outerStream is opened: 1 
    
      // outerStream is opened and ready for reading here
    
      return 0;
    }
    

    【讨论】:

      猜你喜欢
      • 2016-03-01
      • 1970-01-01
      • 2020-08-04
      • 1970-01-01
      • 2022-10-24
      • 1970-01-01
      • 2023-02-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多