I have an API that returns unique_ptr<ofstream>an API to the user. I would like to know when the user will finish this thread, so I can take further action on the file they just wrote. It is imperative that the file be closed because the partition will be reinstalled.
This may not be the correct solution to this problem, but right before I return the stream, I will register a callback with register_callback () :
std::unique_ptr<std::ofstream> os(new std::ofstream(name, std::ofstream::out | std::ofstream::trunc | std::ofstream::binary));
os->register_callback(done_callback, 0);
return os;
The callback is defined elsewhere:
void done_callback(std::ios_base::event evt, std::ios_base& str, int idx)
{
}
ios_base:: event , . erase_event, . . , - copyfmt().
, (, /), :
#include <iostream>
#include <fstream>
#include <memory>
void done_callback(std::ios_base::event evt, std::ios_base& str, int idx)
{
std::cout << "Some sort of stream event occurred. Event: " << evt << std::endl;
}
int main(int argc, char* argv[]) {
std::cout << "Opening the stream." << std::endl;
std::unique_ptr<std::ofstream> os(new std::ofstream("test", std::ofstream::out | std::ofstream::trunc | std::ofstream::binary));
std::cout << "Stream is open." << std::endl;
std::cout << "Registering callback." << std::endl;
os->register_callback(done_callback, 0);
std::cout << "Writing to stream." << std::endl;
*(os.get()) << "Hello!\n";
std::cout << "Done writing." << std::endl;
std::cout << "Flushing stream." << std::endl;
os->flush();
std::cout << "Done flushing." << std::endl;
std::cout << "Writing to stream." << std::endl;
*(os.get()) << "Hello!\n";
std::cout << "Done writing." << std::endl;
std::cout << "Closing the stream..." << std::endl;
os->close();
std::cout << "Stream is closed." << std::endl;
}
:
Opening the stream.
Stream is open.
Registering callback.
Writing to stream.
Done writing.
Flushing stream.
Done flushing.
Writing to stream.
Done writing.
Closing the stream...
Stream is closed.
Some sort of stream event occurred. Event: 0