简体   繁体   中英

How to construct struct objects byte by byte in C?

I'm working on creating a very basic version of file system using C. As a part of it, I'm trying to read from disk and store the contents into a struct object . According to the implementation, reading from disk is possible only byte by byte, of type unsigned char * . Let's say size of the struct is N . The goal is to read N bytes from disk and concatenate them to construct an object.

My approach:

struct sample_struct {
    int a;
    char b;
};
    
void read_from_disk(int position, unsigned char* disk_pointer) {
    int struct_size = sizeof(sample_struct);
    sample_struct *s = new sample_struct();
    
    for(int i=0; i<struct_size;i++) {
        *s = *s | (disk_pointer[position + i] << (i*8)); // Error
    }
}

As seen in the simplified code above, I'm reading a byte, shifting it right by 8 bits and concatenating it, to form the full object. I'm getting the following error though: no operator "|" matches these operands -- operand types are: sample_struct | int no operator "|" matches these operands -- operand types are: sample_struct | int

Am I completely off with my approach? What would be the ideal way to do this?

Storing structs (and several other types) directly to a disk in raw format is doable but be aware that it also limits the use of the data to systems (computers, compilers, etc) that are 100% compatible with your specific system.

In general you enter an area where the C standard doesn't define what is going to happen. To do what you want to do you will for instance violate the strict aliasing rule .

Anyway... to do this you need a unsigned char* pointing to the location of the struct and then fill the struct memory using that pointer.

Like:

unsigned char * struct_alias = (unsigned char *)s;
for(int i=0; i<struct_size;i++) {
    struct_alias[i] = disk_pointer[position + i];
}

Just to repeat: This is non-standard C and consequently it's not portable code.

There are several problems involved, eg struct size may differ on different systems, endianess may differ on different systems, some systems may have trap representation, etc...

That said, it's very common for low level code to be system specific.

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