C++ 如何使用c ++逐字节写入文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20400128/
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 write a file byte by byte using c++
提问by Venkatesan
How to write a file byte by byte using c++?
如何使用c ++逐字节写入文件?
unsigned short array[2]={ox20ac,0x20bc};
if i have a hexadecimal value 0x20ac how can i write it byte by byte in a file using c++
如果我有一个十六进制值 0x20ac,我如何使用 C++ 在文件中逐字节写入它
回答by yasen
You can try something like this:
你可以尝试这样的事情:
#include <fstream>
...
ofstream fout;
fout.open("file.bin", ios::binary | ios::out);
int a[4] = {100023, 23, 42, 13};
fout.write((char*) &a, sizeof(a));
fout.close();
回答by Violet Giraffe
One option, using standard C++ library:
一种选择,使用标准 C++ 库:
#include <fstream>
#include <assert.h>
void main()
{
unsigned short array[2]={ox20ac,0x20bc};
std::ofstream file;
file.open("C:/1.dat", std::ios_base::binary);
assert(file.is_open());
for(int i = 0; i < sizeof(array) / sizeof(array[0]); ++i)
file.write((char*)(array + i * sizeof(array[0])), sizeof(array[0]));
file.close();
}
Alternatively, you can easily write your whole data in one go (without a loop):
或者,您可以轻松地一次性写入全部数据(无需循环):
file.write((const char*)array, sizeof(array));
file.write((const char*)array, sizeof(array));
回答by leewz
To open an output file, use ofstream (output file stream, a subclass of ostream). Use the ios_base::binary mode (as second argument in the constructor or the open() member function) if you're not sure whether your output is human-readable text (ASCII).
要打开输出文件,请使用 ofstream(输出文件流,ostream 的子类)。如果您不确定您的输出是否是人类可读的文本 (ASCII),请使用 ios_base::binary 模式(作为构造函数或 open() 成员函数中的第二个参数)。
To write a single byte, use the ostream member function "put". To write more than one byte at a time, use the ostream member function "write".
要写入单个字节,请使用 ostream 成员函数“put”。要一次写入多个字节,请使用 ostream 成员函数“write”。
There are ways of taking data types (int, for example) longer than one byte and using them as arrays of bytes. This is sometimes called type-punning and is described in other answers, but beware of endianness and different sizes of data types (int can be 2-8 bytes), which can be different on different machines and compilers.
有一些方法可以将数据类型(例如 int)长于一个字节并将它们用作字节数组。这有时被称为类型双关,并在其他答案中进行了描述,但要注意字节序和不同大小的数据类型(int 可以是 2-8 个字节),这在不同的机器和编译器上可能会有所不同。
To test your output, reopen it as an input file and print the bytes.
要测试您的输出,请将其作为输入文件重新打开并打印字节。
ifstream in("myfile.txt", ios_base::binary);
while(!in.eof()) printf("%02X ", in.get()); //print next byte as a zero-padded width-2 capitalized hexadecimal).
in.close();
Or just use a hex editor like normal people.
或者像普通人一样使用十六进制编辑器。
回答by comi
you can use write function or ostream . Use c++ function is ostream.
您可以使用 write 函数或 ostream 。使用c++的函数是ostream。