保持流从一个功能打开到另一个

时间:2012-07-26 19:41:49

标签: c++ file-io stream

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

4 个答案:

答案 0 :(得分:2)

通过引用传递

void myFunction(ifstream &myStream)

答案 1 :(得分:1)

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

答案 2 :(得分:1)

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

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

稍后关闭整个流:stream.close()

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

答案 3 :(得分:0)

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

#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;
}