简体   繁体   中英

Prepend to unsigned char pointer in C?

In CI am reading binary data from a file into a var data like this:

unsigned char *data;
data = malloc(size);
int read_size = fread(data, 1, size, fp);

I want to prepend the var data with <filename><size> of the file. How can I achieve this?
It's not a legal C string because it's binary data with null bytes potentially all over the place.

I know to make sure I allocate it with enough memory, I just can't figure out how to actually prepend it.

  1. Allocate enough memory to data .
  2. Copy the prefix into it.
  3. Get a reference to just behind what had been copied in 2..
  4. Pass this reference to fread() .

Define your own data format for storage:

<uint64_t datalength><string name><char[datalength] contents>

Or for easier in-app use:

struct named_file {
    char* contents;
    uint64_t datasize;
    char name[]; // contents begin directly after the name.
}
  1. Allocate the struct with enough space: sizeof(named_file)+strlen(_name)+1+_datasize
  2. strcpy(name, _name)
  3. contents = name+strlen(name)+1
  4. save data to contents-pointer. memcpy() , direct reading, whatever.

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