写函数不使用seekp值 [英] Write function not using the seekp value
问题描述
我正在尝试使用C ++在文件中的特定位置写入条目
I'm trying to use C++ to write an entry in a specific place in a file
基本上我有
ofstream ofs("file.dat", ios::binary | ios::app);
ofs.seekp(220, ios::beg);
ofs.write((char *)&i, sizeof(i));
但是无论我做什么,它总是写在文件末尾.
But no matter what I do it always write at the end of the file.
我认为这与iso::app
有关,因为根据文档
I suppose this is related to iso::app
because according to the documentation
app (append) Set the stream's position indicator to the end of the stream before each output operation
但是,如果我使用 ate 或不执行任何操作,它将始终删除文件的内容.
But if I use ate or nothing it always erases the content of the file.
任何帮助都会很棒:)
推荐答案
是的,正是ios::app
导致了这种行为.将其替换为ios::in | ios::out
.
Yes, it's the ios::app
that's causing this behaviour. Replace it with ios::in | ios::out
.
编辑:您的问题尚不清楚,但是您的注释表明您正在尝试插入数据到文件中间,而不是覆盖文件的一部分.如果确实如此,您几乎必须为此使用第二个文件.
edit: It wasn't clear from your question, but your comments suggest that you're trying to insert data in the middle of the file, rather than overwrite a portion of the file. If that is indeed the case, you pretty much have to use a second file for that.
这篇关于写函数不使用seekp值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!