C++ 使用 write() 将无符号字符写入二进制文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6995971/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 21:06:31  来源:igfitidea点击:

Writing unsigned chars to a binary file using write()

c++file-iobinary

提问by c0da

I was making a program that read binary files. So, I read the individual bytes into unsigned chars (actually reading the data as chars and casting them to unsigned chars for each character). Now I have to write back the unsigned chars to the binary file.

我正在制作一个读取二进制文件的程序。因此,我将单个字节读入无符号字符(实际上将数据作为字符读取并将它们转换为每个字符的无符号字符)。现在我必须将无符号字符写回二进制文件。

The problem is that now I am forced to write individual bytes after casting them to chars (because write() for binary files expects char* buffer). So, now i have to do the following:

问题是现在我被迫在将它们转换为字符后写入单个字节(因为二进制文件的 write() 需要 char* 缓冲区)。所以,现在我必须执行以下操作:

for(int x=0; x<data_size; x++)
{
    ch=(char)data[x];
    outfile.write(&ch,1);
}

Is there any way to get around this thing so that the amount of I/O operations are reduced in case of reading and writing?

有什么办法可以解决这个问题,以便在读写的情况下减少 I/O 操作的数量?

回答by 6502

You can do the casting on a pointer...

您可以在指针上进行转换...

outfile.write((char *)&data[0], data_size);

the same can be done for reading (i.e. just pass a pointer to the first element of an array of unsigned char casting it to a pointer to char).

读取也可以这样做(即,只需传递一个指向 unsigned char 数组的第一个元素的指针,将其转换为指向 char 的指针)。

回答by Armen Tsirunyan

The type of outfileis ofstream, right? ofstreamis a typedeffor,

的类型outfileofstream,对吧?ofstreamtypedef为了,

typedef std::basic_ofstream<char, std::char_traits<char> > ofstream;

You need your own typedef,

你需要自己的typedef

typedef std::basic_ofstream<unsigned char, std::char_traits<unsigned char> > uofstream;

And then,

进而,

uofstream outfile(...);
outfile.write(data, data_size); //no need to cast

回答by Nobody

When datais of type unsigned char*or unsigned char[]and you just want to write the bits into the file do a pointer cast:

data属于unsigned char*or类型unsigned char[]并且您只想将位写入文件时进行指针转换:

for(int x=0; x<data_size; x++)
{
outfile.write((char*)data + x, 1);
}

As casting removes the issue of one at a time writing:

由于铸造消除了一次写作的问题:

outfile.write((char*)data, data_size);

And you do it all at once. Note that this outdoes the type checking and therefore is not the best solution.

而且您可以一次性完成所有操作。请注意,这超出了类型检查,因此不是最佳解决方案。