简体   繁体   English

在C中读取二进制文件

[英]Reading Binary file in C

I am having following issue with reading binary file in C. 我在C中读取二进制文件有以下问题。

I have read the first 8 bytes of a binary file. 我已经读过二进制文件的前8个字节。 Now I need to start reading from the 9th byte. 现在我需要从第9个字节开始读取。 Following is the code: 以下是代码:

fseek(inputFile, 2*sizeof(int), SEEK_SET);

However, when I print the contents of the array where I store the retrieved values, it still shows me the first 8 bytes which is not what I need. 但是,当我打印存储检索值的数组的内容时,它仍然显示前8个字节,这不是我需要的。

Can anyone please help me out with this? 有人可以帮我解决这个问题吗?

Assuming: 假设:

FILE* file = fopen(FILENAME, "rb");
char buf[8];

You can read the first 8 bytes and then the next 8 bytes: 您可以读取前8个字节,然后读取接下来的8个字节:

/* Read first 8 bytes */
fread(buf, 1, 8, file); 
/* Read next 8 bytes */
fread(buf, 1, 8, file);

Or skip the first 8 bytes with fseek and read the next 8 bytes (8 .. 15 inclusive, if counting first byte in file as 0): 或者使用fseek跳过前8个字节并读取接下来的8个字节(如果将文件中的第一个字节计为0,则包括8 ... 15):

/* Skip first 8 bytes */
fseek(file, 8, SEEK_SET);
/* Read next 8 bytes */
fread(buf, 1, 8, file);

The key to understand this is that the C library functions keep the current position in the file for you automatically. 理解这一点的关键是C库函数会自动保留文件中的当前位置 fread moves it when it performs the reading operation, so the next fread will start right after the previous has finished. fread在执行读取操作时移动它,因此下一个fread将在前一个完成之后立即开始。 fseek just moves it without reading. fseek只是移动它而不阅读。


PS: My code here reads bytes as your question asked. PS:我的代码在这里读取问题所需的字节 (Size 1 supplied as the second argument to fread ) (作为fread的第二个参数提供的大小1)

fseek just moves the position pointer of the file stream; fseek只是移动文件流的位置指针; once you've moved the position pointer, you need to call fread to actually read bytes from the file. 一旦你移动了位置指针,你需要调用fread来实际读取文件中的字节。

However, if you've already read the first eight bytes from the file using fread , the position pointer is left pointing to the ninth byte (assuming no errors happen and the file is at least nine bytes long, of course). 但是,如果您已经使用fread从文件中读取了前八个字节,则位置指针指向第九个字节(假设没有错误发生,文件长度至少为9个字节)。 When you call fread , it advances the position pointer by the number of bytes that are read. 当你调用fread ,它会使位置指针前进一个读取的字节数。 You don't have to call fseek to move it. 您无需致电fseek移动它。

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

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