Reputation: 47
Is there any way to keep a stream (to read or write in a file) open from a function to another in C++?
Upvotes: 0
Views: 5229
Reputation: 6427
Since C++11 file stream got move constructor (6). You can use it to pass opened stream between functions. Consider the following code snippet:
#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
Consider the next code to illustrate the usage of 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;
}
Upvotes: 2
Reputation: 2818
Yes, you can either create the stream outside of the functions and pass it as a parameter to the methods:
void myFunction(ifstream &stream) {...}
Later close the stream when you are done with it: stream.close()
.
Or create the stream within the first function and return it to the calling method and then pass it to the second function.
Upvotes: 2
Reputation: 8285
Make it global or pass it as an argument but ensure that if you pass it as an argument you past it by reference not by value! If you pass it by value the compiler will NOT complain and weird things start happening.
Upvotes: 1