如何将字节类型的字符数组数据保存到 C++ 中的文件中?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11249859/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to save a byte type char array data to a file in c++?
提问by user1486008
I have a char
type array[100]
with 100
bytes stored in it. I want to write this char
type byte array to a file. How could I do this?
我有一个char
类型,array[100]
其中100
存储了字节。我想将此char
类型的字节数组写入文件。我怎么能这样做?
I am not writing to a .txt
file but some other format.
我不是在写入.txt
文件,而是在写入其他格式。
Thank you.
谢谢你。
回答by Rob?
Some people object to using <cstdio>
, so it is worth mentioning how one might use <fstream>
:
有些人反对使用<cstdio>
,因此值得一提的是如何使用<fstream>
:
{
std::ofstream file("myfile.bin", std::ios::binary);
file.write(data, 100);
}
The four lines above could be combined into this single line:
上面的四行可以合并为一行:
std::ofstream("myfile.bin", std::ios::binary).write(data, 100);
回答by Rafael Baptista
No need to get complicated. Just use good old fwrite directly:
没有必要变得复杂。直接使用旧的 fwrite 即可:
FILE* file = fopen( "myfile.bin", "wb" );
fwrite( array, 1, 100, file );
回答by Jerry Coffin
Based on the (little) information you've provided, one possibility would be to write the array to the file in binary format, such as:
根据您提供的(小)信息,一种可能性是以二进制格式将数组写入文件,例如:
std::ofstream out("somefile.bin", std::ios::binary);
out.write(array, sizeof(array));