简体   繁体   中英

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. 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). 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. The 16-24 bytes in this file, contains the file length of the original file, as an unsigned integer in network byte order.

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
  • You may need to deal with endiannes .
  • There is no error checking whatsoever in this example.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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