C++ IO二进制文件流:未指定输出时的默认值
我的问题是关于二进制文件 I/O。假设运行以下代码:
#include <iostream>
#inclide <fstream>
int main(){
fstream out;
out.open("binfile.bin",ios::binary|ios::out);
if(!out.good()){
cout<<"ain't good"<<endl;
return EXIT_FAILURE;
}
out.seekp(3);
out<<char(74);
out.seekp(7);
out<<char(73);
out.close();
}
binfile.bin 包含 00 00 00 4A 00 00 00 49
,正如预期的那样。如果我不指定输出内容,我可以以某种方式更改放入文件中的默认值吗?我想将 00
替换为 30
之类的内容,以便 binfile.bin 包含 30 30 30 4A 30 30 30 49
,是这样吗可行吗?当然,我可以在末尾循环遍历文件,并将所有 00
替换为 30
,但我想避免这种情况。
My question is about binary file I/O. Suppose the following code is run:
#include <iostream>
#inclide <fstream>
int main(){
fstream out;
out.open("binfile.bin",ios::binary|ios::out);
if(!out.good()){
cout<<"ain't good"<<endl;
return EXIT_FAILURE;
}
out.seekp(3);
out<<char(74);
out.seekp(7);
out<<char(73);
out.close();
}
binfile.bin contains 00 00 00 4A 00 00 00 49
, as expected. Can I somehow change that default value that is placed into the file if I don't specify what to output? I would like to replace 00
with something like 30
, so that binfile.bin would contain 30 30 30 4A 30 30 30 49
, is that doable? Of course I can loop through the file at the end and replace all 00
s with 30
s, but I'd like to avoid that.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以为
seekp
编写一个包装器并使用它。伪代码:You could write a wrapper for
seekp
and use that. Pseudocode:如果您分配一个 char buf[4] 数组,为所有元素设置所需的“填充”值,然后只需使用您的值更新第一个/最后一个元素,而不是使用 << 来查找和写入 char 值,会怎样?想要并调用 out.write(buf, 4) 吗?
Instead of seeking and writing value as char using <<, what if you allocate a char buf[4] array, set your desired 'fill' value for all the elements, then just update the first/last element with the value you want and call out.write(buf, 4)?