c++ - Automatically extend file size when seeking / writing to a location on a read/write fstream -
i'm working on legacy code uses win32 writefile() write random location in binary file. offset of write can past end of file in case writefile() seems automatically extend file size offset , write data file.
i'd use std::fstream same, when try seekp() appropriate location, past end of file, seekp() fails , subsequent write() fails well.
so seems me have 'manually' fill in space between current eof , location want write to.
the code looks this:
void save(size_t offset, const element& element) { m_file.seekp(offset, std::ios_base::beg); m_file.write(reinterpret_cast<const char*>(&element), sizeof(element)); if (m_file.fail()) { // ... error handling } } so option 'manually' write 0s current eof offset?
here example picked verbatim msdn:
// basic_ostream_seekp.cpp // compile with: /ehsc #include <fstream> #include <iostream> int main() { using namespace std; ofstream x("basic_ostream_seekp.txt"); streamoff = x.tellp(); cout << << endl; x << "testing"; = x.tellp(); cout << << endl; x.seekp(2); // put char in third char position in file x << " "; x.seekp(2, ios::end); // put char 2 after end of file x << "z"; } the file "basic_ostream_seekp.txt" has te ting\0\0z @ end of program, i.e., allowed seek past end of file.
in case, if write fail you, check , see if seekp too. if does, can detect failure earlier.
Comments
Post a Comment