C ++读取二进制文件 [英] C++ reading binary files
问题描述
我想了解如何在C ++中读取二进制文件.我的代码:
I want to understand how does reading binary files work in C++. My code:
int main() {
ifstream ifd("input.png",ios::binary |ios::ate);
int size = ifd.tellg();
ifd.seekg(0, ios::beg);
vector<char> buffer;
buffer.reserve(size);
ifd.read(buffer.data(), size);
cout << buffer.data();
return 0;
}
我认为如果我退出缓冲区,我将以二进制形式获取结果,但事实并非如此.
I thought that if I cout my buffer I would get the result in binary but that is not the case.
我的输出是:˙Ř˙á6Exif
My output is: ˙Ř˙á6Exif
如果我阅读了文本文件,它将以正常形式而不是二进制形式显示文本.显然我的逻辑不对.如何将文件读取到缓冲区中,使其包含二进制值?P.s.我这样做是为了实现Shannon-Fano算法,因此,如果有人对读取二进制文件有任何建议,我将不胜感激.
And if I read the text file it displays the text in normal form not in binary. Obviously my logic is not right here. How can I read files to a buffer so it will contain binary values? P.s. I`m doing this for implementing a Shannon-Fano algorithm so if anyone has any advice on reading a binary file I would be grateful.
推荐答案
您需要调整向量的大小,而不是保留向量:
You need to resize your vector, not reserve it:
int main()
{
ifstream ifd("input.png", ios::binary | ios::ate);
int size = ifd.tellg();
ifd.seekg(0, ios::beg);
vector<char> buffer;
buffer.resize(size); // << resize not reserve
ifd.read(buffer.data(), size);
cout.write(buffer.data(), buffer.size()); // you cannot just output buffer to cout as the buffer won't have '\0' ond-of-string terminator
}
否则,您的代码会尝试将 size
个字符读取到一个空缓冲区中.您也可以使用设置向量大小的向量构造函数: vector< char>缓冲区(大小);
Otherwise your code tries to read size
characters into an empty buffer. You may as well use vector constructor that sets vector size: vector<char> buffer(size);
您可以通过以下方式输出缓冲区的字节值:
You can output byte values of your buffer this way:
void dumpbytes(const vector<char>& v)
{
for (int i=0; i<v.size(); ++i)
{
printf("%u ", (unsigned char)v[i]);
if ((i+1) % 16 == 0)
printf("\n");
}
printf("\n");
}
或者像普通十六进制编辑器一样为十六进制输出做的事情:
Or something like common hex editors do for hex output:
void dumphex(const vector<char>& v)
{
const int N = 16;
const char hex[] = "0123456789ABCDEF";
char buf[N*4+5+2];
for (int i = 0; i < v.size(); ++i)
{
int n = i % N;
if (n == 0)
{
if (i)
puts(buf);
memset(buf, 0x20, sizeof(buf));
buf[sizeof(buf) - 2] = '\n';
buf[sizeof(buf) - 1] = '\0';
}
unsigned char c = (unsigned char)v[i];
buf[n*3+0] = hex[c / 16];
buf[n*3+1] = hex[c % 16];
buf[3*N+5+n] = (c>=' ' && c<='~') ? c : '.';
}
puts(buf);
}
使用"Hello World!"缓冲数据将打印如下:
Buffer with "Hello World!" data would be printed as follows:
48 65 6C 6C 6F 20 57 6F 72 6C 64 21 Hello World!
这篇关于C ++读取二进制文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!