从文件输出原始字节时,第一个字节已损坏
Outputting raw bytes from a file, first byte is corrupted
所以我写了一个小程序,将文件的内容读入char数组(因为fstream似乎只支持char指针)。我想做的是将原始字节发送到控制台。AFAIK char 是 8 位数据类型,因此不应太难。但是,如果我只打印数组的成员,我会得到与 ASCII 值对应的字符,所以我使用的是静态强制转换。这工作正常,除了第一个字节似乎没有正确转换。我正在使用 PNG 文件作为测试.bin文件。PNG 文件始终以字节序列 137,80,78,71,13,10,26,10 开头。但是,第一个字节打印不正确。我有一种感觉,它必须与值超过 127 做一些事情。但是,我无法将读取缓冲区数据类型更改为其他任何类型(例如无符号字符或无符号短整型),因为来自 fstream 的 foo.read() 仅支持 char 目标缓冲区。如何让 fstream 将原始字节读取为可用的无符号类型?
我的代码:
#include <iostream>
#include <fstream>
#include <sys/stat.h>
#define filename "test.bin"
void pause(){
std::string dummy;
std::cout << "Press enter to continue...";
std::getline(std::cin, dummy);
}
int main(int argc, char** argv) {
using std::cout;
using std::endl;
using std::cin;
// opening file
std::ifstream fin(filename, std::ios::in | std::ios::binary);
if (!fin.is_open()) {
cout << "error: open file for input failed!" << endl;
pause();
abort();
}
//getting the size of the file
struct stat statresults;
if (stat(filename, &statresults) == 0){
cout<<"File size:"<<statresults.st_size<<endl;
}
else{
cout<<"Error determining file size."<<endl;
pause();
abort();
}
//setting up read buffer and reading the entire file into the buffer
char* rBuffer = new char[statresults.st_size];
fin.read(rBuffer, statresults.st_size);
//print the first 8 bytes
int i=0;
for(i;i<8;i++) {
cout<<static_cast<unsigned short>(rBuffer[i])<<";";
}
pause();
fin.clear();
fin.close();
delete [] rBuffer;
pause();
return 0;
}
-119 有符号是 137 无符号(二进制都是 1000 1001)。
这被符号扩展到短 1111 1111 1000 1001,即 65,417 个无符号。
我假设这就是你所看到的价值。
读入无符号缓冲区:
unsigned char* rBuffer = new unsigned char[statresults.st_size];
fin.read(reinterpret_cast<char*>(rBuffer), statresults.st_size);
尝试 fin.read() 以外的其他方法怎么样?
而不是:
char* rBuffer = new char[statresults.st_size];
fin.read(rBuffer, statresults.st_size);
您可以使用:
unsigned char* rBuffer = new unsigned char[statresults.st_size];
for(int i = 0; i < statresults.st_size; i++)
{
fin.get(rBuffer[i]);
}
您可能希望使用无符号字符作为"字节"。你可以尝试这样的事情:
using byte = unsigned char;
...
byte* buffer = new byte[statresults.st_size];
fin.read( reinterpret_cast<char*>( buffer ), statresults.st_size );
...
delete[] buffer;
相关文章:
- 为什么它只打印双链接列表的第一个值,而我的程序却崩溃了
- std::find,返回所有找到的值的替代方法,而不仅仅是存在重复的向量的第一个值
- 如何仅读取文本文件中的第一个值
- 在C++中,如何在第一个"system()"结束后执行第二个"system()"?
- 查找不在标准中的第一个值::设置<int>最小-最大值
- C++:忽略第一个 cin.ignore 之后的输入
- 在C++中打印多个矢量的第一个值
- C++去除前x个元素的有效方法,在不改变向量大小的情况下将第x+1个元素推到第一个
- C++第一个cout将不会打印
- 我们可以在第一个else-if条件结束后使用另一个else-if条件吗
- OpenGL:第二个VBO破坏了第一个VBO
- 为什么第一个Dynamic_cast没有投射到基类?
- OpenGL 2D游戏只绘制第二个精灵纹理而不是第一个
- C++ 为什么程序只读取第一个值
- 在我的第一个C++程序中需要一些帮助(简单)
- 为什么我的代码在第一个 if 语句处中断?
- 是否可以从另一个类对象调用一个类函数而不继承第一个类
- 无法使我的第一个Windows OpenGL窗口抬起并运行
- 将参数初始化为构造函数,而不是第一个
- 无法在硬件模式下创建 SGX 安全区 - "invalid launch token"即使文档将无效的启动令牌指定为第一个