简体   繁体   English

C二进制文件读取:我应该移动多少字节?

[英]C Binary File Reading: How many bytes should I move?

Suppose I have a program that works with binary files in C language. 假设我有一个使用C语言的二进制文件的程序。

Suppose I have 8 objects (each object is a struct record type) in this binary file, and I have read the first 3 objects of the 8. (By reading 3 objects of the 8 I mean I have read it and store them into an array) 假设我在此二进制文件中有8个对象(每个对象是一个struct记录类型),并且我已经读取了8个对象的前3个对象。(通过读取8个对象中的3个对象,我是说我已经读取并存储到一个对象中。阵列)

I know in order to read later content of the binary file, I have to use fseek call to achieve this goal. 我知道为了以后读取二进制文件的内容,我必须使用fseek调用来实现这个目标。 What I feel confused is this, suppose I want to read the 4th object of the 8, how many bytes/objects should I move/skip using fseek call? 我感到困惑的是,假设我想读取8的第4个对象,我应该使用fseek调用移动/跳过多少个字节/对象?

Should I call 我应该打电话吗?

fseek(fp, sizeof(struct record) * 3, SEEK_SET);

or 要么

fseek(fp, sizeof(struct record) * 4, SEEK_SET);

it's usually best to write these things down to get a sense of how the memory mapping works, so let's try and represent the file (assuming each struct is 4 bytes in size): 通常最好先编写这些内容以了解内存映射的工作原理,让我们尝试表示文件(假设每个结构的大小为4个字节):

byte:   |A-0|A-1|A-2|A-3|B-0|B-1|B-2|B-3|C-0|C-1|C-2|C-3|D-0|D-1|D-2|D-3|E....
        ----------------------------------------------------------------------
struct: | struct A      |struct B       |struct C       |struct D       |s...
        ----------------------------------------------------------------------
address:0   1   2   3   4   5   6   7   8   9  10   11  12  13  14  15  16

as you can see from the visual representation, the file is 0-based indexed ie the first struct is located at address 0 (sizeof(struct record) * 0) the second is located at address 4 (sizeof(struct record) *1) and so on... 从视觉表示中可以看到,文件是从0开始的索引,即第一个结构位于地址0 (sizeof(struct record) * 0) ,第二个结构位于地址4 (sizeof(struct record) *1)等等...

from here one can derive for the nth element offset = ( sizeof(struct record) * ( n - 1) ) 从这里可以推导出第n个元素offset = ( sizeof(struct record) * ( n - 1) )

hope it makes it clearer... 希望它能让它更清晰......

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

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