简体   繁体   English

C:来自二进制文件的fread与原始模式不匹配后存储到缓冲区中的unsigned short

[英]C: unsigned short stored into buffer after fread from a binary file doesn't match original pattern

I have a binary file filled with 2-byte words following this pattern(in HEX): 0XY0. 我有一个二进制文件,在这个模式后面填充2字节字(在HEX中):0XY0。 this is the part of the code where I execute fread and fopen. 这是我执行fread和fopen的代码的一部分。

unsigned short buffer[bufferSize]; 
FILE *ptr;                          //

ptr = fopen(fileIn,"rb");           //

if(ptr == NULL)
{
    fprintf(stderr,"Unable to read from file %s because of %s",fileIn,strerror(errno));
    exit(20);
}

size_t readed = fread(buffer,(size_t)sizeof(unsigned short),bufferSize,ptr);
if(readed!=bufferSize)
{
    printf("readed and buffersize are not the same\n");
    exit(100);
}
//---------------------------

If I look at any content of the buffer, for example buffer[0], instead of being a short with pattern 0XY0, it is a short with pattern Y00X Where is my error? 如果我查看缓冲区的任何内容,例如buffer [0],而不是模式0XY0的短路,它是模式Y00X的短路我的错误在哪里? is it something regarding endianess? 这是关于endianess的东西吗? of course i checked every element inside buffer. 当然我检查了缓冲区内的每个元素。 the program execute with no errors. 程序执行没有错误。

EDIT: If i read from file with size char instead of short, the content of buffer(obviously changed to char buffer[bufferSize*2];) match the pattern OXYO. 编辑:如果我从文件读取大小字符而不是短,缓冲区的内容(显然更改为字符缓冲区[bufferSize * 2];)匹配模式OXYO。 So I have that (for example) buffer[0] is 0X and buffer[1] is Y0 所以我有(例如)buffer [0]为0X,缓冲区[1]为Y0

Your problem seems to be exactly typical of an endianness mismatch between the program that stored the data into the file and the one that reads it. 您的问题似乎是将数据存储到文件中的程序与读取它的程序之间的字节顺序不匹配的典型问题。 Remember that mobile phone processors tend to use big-endian representations and laptop little-endian. 请记住,手机处理器倾向于使用big-endian表示和笔记本电脑little-endian。

Another potential explanation is your file might have been written in text mode by a windows based program that converted the 0x0A bytes into pairs of 0x0D / 0x0A , causing the contents to shift and cause a similar pattern as what you observe. 另一个可能的解释是您的文件可能是由基于Windows的程序以文本模式写入的,该程序将0x0A字节转换为0x0D / 0x0A对,从而导致内容移位并产生与您观察到的类似的模式。

Instead of reading the file with fread , you should read it byte by byte and compute the values according the endianness specified for the file format. 您应该逐字节读取它,而不是使用fread读取文件,并根据为文件格式指定的字节顺序计算值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM