从二进制文件中逐个读取字节

时间:2012-07-11 14:51:42

标签: c++ file-io binary byte

这是我的问题,我想打开一个.jpg文件并将每个字节写为以逗号分隔的十进制数字(0-255)到另一个.txt文件中。现在它应该能够使用该txt文件再次构建.jpf文件。这就是我试图做到的。

#include<iostream>
#include<fstream>
using namespace std;
int main()
{
long x;
char *s;

ifstream ifs("image.jpg",ios::binary);
ifs.seekg(0,ios::end);
x=ifs.tellg();
ifs.seekg(0,ios::beg);

s=new char[x];
ifs.read(s,x);
ifs.close();

ofstream is("image.txt");

for(int i=0;i<x;i++){
is<<(unsigned int)s[i]<<",";
}

现在这个程序创建了带有十进制数字的image.txt,如下所示,  4294967295,4294967256,4294967295,4294967264,0,16,74,70,73,70,0,1,...... 这里有些数字似乎是4字节长,s [i]只指一个字节,所以怎么能(int)s [i]返回一个大于255的数字。请有人帮我这个....谢谢..

1 个答案:

答案 0 :(得分:13)

您的计算机上似乎char 已签名。因此,当您将负数转换为unsigned int时,您会获得很大的价值。使用char表示输出中的大值是负值。请注意,当char 签名时,其值可以是-128127,但字节可以在{{1}之间到0。因此,任何大于255的值都会在范围127之间变为负值。

-128 to -1用作:

unsigned char

或者这样做:

unsigned char *s;

即,先将is<< static_cast<unsigned int> (static_cast<unsigned char>(s[i]) )<<","; ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ casting to unsigned char first ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ then casting to unsigned int 投放到char,然后投放到unsigned char


那就是你所面临的问题。现在有关于风格和习语的一些注释。在C ++中,您应该尽可能避免使用unsigned int。在您的情况下,您可以使用new作为:

std::vector

最后一行将文件中的所有数据读入//define file stream object, and open the file std::ifstream file("image.jpg",ios::binary); //prepare iterator pairs to iterate the file content! std::istream_iterator<unsigned char> begin(file), end; //reading the file content using the iterator! std::vector<unsigned char> buffer(begin,end); 。现在您可以将它们打印为:

buffer

要使所有这些工作正常,您需要在代码中添加以下标题:

std::copy(buffer.begin(), 
          buffer.end(), 
          std::ostream_iterator<unsigned int>(std::cout, ","));

正如您所看到的,这个惯用的解决方案不使用指针#include <vector> //for vector #include <iterator> //for std::istream_iterator and std::ostream_iterator #include <algorithm> //for std::copy ,也不使用 cast

相关问题