用C语言读取二进制文件

发布于 2024-08-27 02:34:45 字数 221 浏览 4 评论 0原文

我在 C 中读取二进制文件时遇到以下问题。

我已读取二进制文件的前 8 个字节。现在我需要从第 9 个字节开始读取。以下是代码:

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

但是,当我打印存储检索到的值的数组的内容时,它仍然显示前 8 个字节,这不是我需要的。

谁能帮我解决这个问题吗?

I am having following issue with reading binary file in C.

I have read the first 8 bytes of a binary file. Now I need to start reading from the 9th byte. 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.

Can anyone please help me out with this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

多孤肩上扛 2024-09-03 02:34:45

假设:

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

您可以读取前 8 个字节,然后读取接下来的 8 个字节:

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

或者使用 fseek 跳过前 8 个字节并读取接下来的 8 个字节(包括 8 .. 15,如果计算文件中的第一个字节) as 0):

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

理解这一点的关键是 C 库函数会自动为您保留文件中的当前位置fread 在执行读取操作时移动它,因此下一个 fread 将在前一个完成后立即开始。 fseek 只是移动它而不读取。


PS:按照您的问题,我的代码读取字节。 (大小 1 作为 fread 的第二个参数提供)

Assuming:

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

You can read the first 8 bytes and then the next 8 bytes:

/* 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):

/* 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. fread moves it when it performs the reading operation, so the next fread will start right after the previous has finished. fseek just moves it without reading.


P.S.: My code here reads bytes as your question asked. (Size 1 supplied as the second argument to fread)

默嘫て 2024-09-03 02:34:45

fseek 只是移动文件流的位置指针;移动位置指针后,您需要调用 fread 来实际从文件中读取字节。

但是,如果您已经使用 fread 从文件中读取了前八个字节,则位置指针将指向第九个字节(假设没有发生错误并且文件至少有九个字节长,当然)。当您调用fread时,它会将位置指针前进所读取的字节数。您不必调用 fseek 来移动它。

fseek just moves the position pointer of the file stream; once you've moved the position pointer, you need to call fread to actually read bytes from the file.

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). When you call fread, it advances the position pointer by the number of bytes that are read. You don't have to call fseek to move it.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文