简体   繁体   English

从 C 中的文件中读取一定范围的字节

[英]Reading a range of bytes from a file in C

I'm trying to write a program that takes a file, and reads bytes from it in different intervals, and assigns them to a variable.我正在尝试编写一个程序,该程序接受一个文件,并以不同的时间间隔从中读取字节,并将它们分配给一个变量。 This is what I currently have:这是我目前拥有的:

struct casc_file_parsed {
    unsigned int targetsize;
    uint64_t blocksize;
    uint64_t blockcount;
    csc_block_t* blocks;
};
struct casc_file_parsed parsed_casc_file;
FILE* fpc = fopen(casc_file_data, "r");

char c;
char str[MAX];
int i = 0;
int j = 0;

for(i = 0; i >= 24; i++) {
    if(i >= 16 && i <= 24) {    
        str[j] = c;
        j++;
    }
    c = fgetc(fp);
}
parsed_casc_file.targetsize = str;

I haven't tested it yet, since I know it isn't complete yet, and other functionalities needs to be added before it can run.我还没有测试它,因为我知道它还没有完成,在它可以运行之前需要添加其他功能。 What I am trying to do in this approach is creating a loop, and if I is the interval of 16-24, it saves the current byte to an array str.我在这种方法中试图做的是创建一个循环,如果我是16-24的间隔,则将当前字节保存到数组str。 The array then needs to be transformed into an int, and saved in the struct (I am aware that the bottom line won't work).然后需要将数组转换为 int,并保存在结构中(我知道底线不起作用)。 I'm not sure if this is the best approach, but I could really use some input right now, if there is a better way or I am missing anything.我不确定这是否是最好的方法,但我现在真的可以使用一些输入,如果有更好的方法或者我遗漏了什么。

EDIT: The .cascade file is a 64-byte file, containing a list of hashes describing another file.编辑: .cascade 文件是一个 64 字节的文件,包含描述另一个文件的哈希列表。 The 16-24 bytes in this file, contains the file length of the original file, as an unsigned integer in network byte order.此文件中的 16-24 个字节,包含原始文件的文件长度,为网络字节顺序中的无符号整数。

You probably need something like this:你可能需要这样的东西:

  ...
  FILE* fpc = fopen(casc_file_data, "rb");  // use "rb" just to be sure you're reading
                                            // binary. It's mandatory on some platforms

  fseek(fpc, 16, SEEK_SET);        // goto offset 16
  char buffer[8];                  
  fread(buffer, 8, 1, fpc);        // read 8 bytes (which are a 64 bit integer)

  uint64_t rawsize;
  memcpy(&rawsize, buffer, 8);     // copy bytes read to 64 bit variable

  unsigned int targetsize = (unsigned int)rawsize;  // convert to unsigned int
  ...
  fclose(fpc);

Disclaimers:免责声明:

  • I suppose that the 8 bytes in offsets 16 to 24 are actually a 64 bit number我想偏移量 16 到 24 中的 8 个字节实际上是一个 64 位数字
  • You may need to deal with endiannes .您可能需要处理endiannes
  • There is no error checking whatsoever in this example.在这个例子中没有任何错误检查。

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

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