[英]C++ Binary file read issue
I was making a function to read a file containing some dumped data (sequence of 1 byte values). 我正在创建一个函数来读取包含一些转储数据的文件(1个字节值的序列)。 As the dumped values were 1 byte each, I read them as chars.
由于转储值各为1个字节,因此我将它们视为字符。 I opened the file in binary mode, read the data as chars and did a casting into int (so I get the ascii codes).
我以二进制模式打开文件,将数据读取为字符并进行转换为int(因此我得到了ascii代码)。 But the data read isn't correct (compared in a hex-editor).
但是读取的数据不正确(在十六进制编辑器中进行比较)。 Here's my code:
这是我的代码:
int** read_data(char* filename, int** data, int& height, int& width)
{
data=new int*[height];
int row,col;
ifstream infile;
infile.open(filename,ios::binary|ios::in);
if(!infile.good())
{
return 0;
}
char* ch= new char[width];
for(row=0; row<height; row++)
{
data[row]=new int[width];
infile.read(ch,width);
for(col=0; col<width; col++)
{
data[row][col]=int(ch[col]);
cout<<data[row][col]<<" ";
}
cout<<endl;
}
infile.close();
return data;
}
Any ideas what might be wrong with this code? 任何想法这个代码可能有什么问题? My machine is windows, I'm using Visual Studio 2005 and the (exact) filename that i passed is:
我的机器是Windows,我使用的是Visual Studio 2005,我传递的(确切)文件名是:
"D:\\files\\output.dat"
EDIT : If I don't use unsigned char, the first 8 values, which are all 245, are read as -11. 编辑 :如果我不使用unsigned char,前8个值(全部为245)将读为-11。
I think, you might have to use unsigned char and unsigned int to get correct results. 我想,您可能必须使用unsigned char和unsigned int来获得正确的结果。 In your code, the bytes you read are interpreted as signed values.
在您的代码中,您读取的字节被解释为有符号值。 I assume you did not intend that.
我假设你不打算这样做。
Your error seems to cover in using of char*
for ch
. 您的错误似乎涵盖了使用
char*
for ch
。 When you try to output it, all chars are printed until the first zero value. 当您尝试输出它时,将打印所有字符,直到第一个零值。
A plain char
can be either signed or unsigned, depending on the compiler. 普通
char
可以是signed或unsigned,具体取决于编译器。 To get a consistent (and correct) result, you can cast the value to unsigned char
before assigning to the int
. 要获得一致(和正确)的结果,可以在赋值给
int
之前将值转换为unsigned char
。
data[row][col]=static_cast<unsigned char>(ch[col]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.