In researching forcing files to be written as quickly as possible, I have seen the following chunk of code in a few places:
_commit(outputFile.rdbuf()->fd());
where outputFile is an std::ofstream object. I am basically doing the following:
std::ofstream outputFile;
outputFile.write((char*)blocks, sizeof(blocks));
outputFile.flush();
_commit(outputFile.fd());
outputFile.close();
blocks is a simply an array of char arrays. What I am doing is writing to an array of char arrays to represent the contents of a binary file, then pushing that array out to the file itself. I need the files to get written as quickly as possible as the medium is somewhat less reliable flash memory and the chance of power outages is unusually high.
When I attempt to compile, I receive the following error on the _commit line of code:
error C2039: 'fd' : is not a member of 'basic_ofstream<char,struct std::char_traits<char> >'
How should I go about getting the file descriptor of outputFile and passing it to _commit?
EDIT: I have changed the above code to reflect using ofstream.fd(), which is supposed to be a public member of ofstream.
Someone should have written this as an answer. They have not so I will steal their glory. 🙂
The file descriptor is implementation dependent. Some systems might not have one. So the C++ Standard does not define any method to get it from a
fstreamorfilebuf.The
_commitfunction in your example is definitely implementation dependent. One big hint is that the name starts with an underscore. A bit of Google shows that_commitonly works on Windows.To get what you want, you could write your own class derived from
streambuf. This customized class would implement IO in the low-level terms that you want to use (Windows, POSIX) and can provide extra functions to return file descriptors or flush data to disk.To use the custom class as a stream you would create a
ostreamand pass it a pointer to yourstreambufclass.