所以我试图读取每个块有4个字节的二进制文件,当我在我的文件上执行hexdump时输出:
0000000 0022 0000 6261 6463 3030 3030 6261 6463
0000010 3030 3030 6261 6463 3030 3030 6261 6463
*
00000d0 3030 3030 6261 6463 3030 3030 000a
00000dd
(每行数字之间不应该有一行,抱歉)
但是当它将这些值读入数组时,这是我得到的输出:
34 61000000 30646362 61303030 30646362 61303030 30646362 61303030 30646362 2283030 0 44c5bbc0 7fff 22 0 14fea515 7f68 0 0 22 0 22 0 4007b2 0 1 0 1000 0 2289010 0 44c5bbc0 7f
我在网上遵循了很多说明,我真的不确定从哪里开始。
以下是我正在使用的代码:
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
int main(int argc, char** argv)
{
unsigned char buffer[1];
FILE *filePointer;
filePointer = fopen(argv[1], "rb");
//unsigned char buffer[filePointer];
int readVal = 0;
readVal = fread(buffer, sizeof(buffer), 1, filePointer);
if (readVal == 0)
{
printf("File did not read anything\n");
}
int size = buffer[0];
/*int i = 1;
for(; i < 1; i++)
{
printf("%x ", buffer[i]);
}
*/
//int size = buffer[0];
printf("%d\n", size);
unsigned int array[size];
int otherDataElements;
otherDataElements = fread(array, sizeof(buffer), size, filePointer);
if (otherDataElements == 0)
{
printf("There was nothing there!");
}
int j = 0;
for (; j < size; j++)
{
printf("%x ", array[j]);
}
return 0;
}
有一些代码被注释掉了,忽略它。谢谢!
答案 0 :(得分:0)
什么是size
?字节数?还是整数?
这似乎很可疑:
otherDataElements = fread(array, sizeof(buffer), size, filePointer);
尝试更改为:
otherDataElements = fread(array, sizeof(unsigned int), size/sizeof(unsigned int), filePointer);
因为数组是无符号整数的array
,而fread
的第二个参数会询问您要读取的每个元素的大小。如果你想将文件内容解释为我认为的4字节整数数组,文件长度也应该是4的倍数。
无论如何,我的机器上的这个程序的输出是(这是类似的程序,因为你刚刚添加了将数据写入文件进行测试 - 我已经简化了阅读):
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
void test()
{
unsigned char buffer[1];
FILE *filePointer;
filePointer = fopen("/Users/macbookair/Documents/test/test/t.bin", "rb");
//unsigned char buffer[filePointer];
//readVal = fread(buffer, sizeof(buffer), 1, filePointer);
//if (readVal == 0)
//{
// printf("File did not read anything\n");
// }
//int size = 4;
/*int i = 1;
for(; i < 1; i++)
{
printf("%x ", buffer[i]);
}
*/
//int size = buffer[0];
//printf("%d\n", size);
unsigned int array[4] = {0};
int otherDataElements;
int nrOfInts = 1; // In this test method we only want to read 1 integer from file, we assume there is one integer only
otherDataElements = fread(array, sizeof(unsigned int), nrOfInts, filePointer);
if (otherDataElements == 0)
{
printf("There was nothing there!");
}
int j = 0;
for (; j < nrOfInts; j++)
{
printf("%x ", array[j]);
}
}
int main(int argc, const char * argv[])
{
// Just do a test write to file. Write 4 bytes to read back later.
FILE *write_ptr;
unsigned char buffer[4] = {0,1,2,3};
write_ptr = fopen("/Users/macbookair/Documents/test/test/t.bin","wb");
fwrite(buffer,sizeof(buffer),1,write_ptr);
fclose(write_ptr);
// Call our method for reading the data
test();
return 0;
}
这样:
3020100
你可以看到输出是交换的,但这是因为字节顺序 - 当我的计算机将字节00 01 02 03解释为整数的字节时,它以小端方式这样做 - 因此输出是整数03020100.你可能想要在你的情况下也考虑这一点。所以在我的情况下,我认为它工作正常。