是否可以仅用c ++更新文件的一部分?
例:
旧文件答: "A''A''A''B''B''C''C''C"
新文件:"A''A''A" "X''X" "C" 'C''C'
因为真实的文件不像这些例子那么小,而且我确实知道究竟发生了什么变化(更改内容的偏移和writeLenght),能够打开文件,将流设置到正确的位置,编写信息并再次关闭文件....但这将导致一个如下所示的文件:
更新文件:'0''0''0''X''X''C''C''C'
这是我使用的代码:
void update file( list<unsigned char> content, int offset){
fs::basic_ofstream< char > fileStream( path , ios::out | ios::binary );
list< unsigned char >::const_iterator contentIter = content.begin();
// begin write operation at the offset
advance( contentIter , offset);
fileStream.seekp( offset );
while( contentIter != content.end() ){
unsigned char value = (char)*contentIter;
fileStream.put( value );
++contentIter;
}
fileStream.close();
Run Code Online (Sandbox Code Playgroud)
有没有办法做到这一点,或者每次更改时都要重写整个文件?
谢谢
你有很多正确的想法.你需要改变的主要是使用a fstream代替ofstream,并ios::in | ios::out在打开它时使用(假设fs::basic_ofstream以某种方式解析std::basic_ofstream).当您打开时,仅ios::out使用现有文件内容被销毁.
编辑:顺便说一句,我很难想象使用std::list<char>是个好主意的情况.在具有32位指针和8位指针的典型计算机上char,您正在考虑使用8倍的空间作为指针,就像您要存储的数据一样,并且您可以访问存储的数据一般来说也很慢.
好的,谢谢:
这是一段工作代码,以防有人遇到同样的问题。
void update file( list<unsigned char> content, int offset, int writeLength){
fs::basic_fstream< char > fileStream( path , ios::out | ios::in | ios::binary );
list< unsigned char >::const_iterator contentIter = content.begin();
// begin write operation at the offset
advance( contentIter , offset);
// set the Stream to the offset position
fileStream.seekp( offset );
while( contentIter != content.end() && writeLength != 0){
unsigned char value = (char)*contentIter;
fileStream.put( value );
++contentIter;
--writeLength;
}
fileStream.close();
}
Run Code Online (Sandbox Code Playgroud)
使用此代码时应该检查错误或告诉流抛出异常......