您需要调整向量的大小,而不是保留它:
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> buffer(size);
您可以通过这种方式输出缓冲区的字节值:
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");
}
或者类似于常见的十六进制编辑器对十六进制输出所做的操作:
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!”数据将打印如下:
48 65 6C 6C 6F 20 57 6F 72 6C 64 21 Hello World!