Reading a binary file in C

The file contains a structure in binary form, first there is an array of char(word), then a number, and all this is repeated from a new line, the number of which is known in advance. The question is simple and at the same time complex, but how to actually count these values (I write them in the structure), until it comes out as I wrote.

 // структура
    
    struct st
    {
        char* nam;
        int count;
    };
    // сама запись в файл
     FILE* fp = fopen("file.bin", "wb+");
        char new_str = '\n';
        if (fp == NULL) {
            printf("Can't open file\n");
            return;
        }
        for (int i = 0; i < size; i++) {
            fwrite(&(st[i].nam), sizeof(char), strlen(st[i].nam), fp);
            fwrite(&(st[i].count), sizeof(int), 1, fp);
            fwrite(&(new_str), sizeof(char), 1, fp);
        }
        fclose(fp);
    
        FILE* fp = fopen("file.bin", "rb");
            if (fp == NULL) {
                printf("Can't open file\n");
                return;
            }
            rewind(fp);
            for (int i = 0; i < size; i++) {
                fread(&(st[i].nam), sizeof(char), strlen(st[i].nam), fp);
                fread(&(st[i].count), sizeof(int), 1, fp);
            }
            fclose(fp);
Author: Mikhail, 2020-10-15

1 answers

When writing, you must first write the number of output bytes of the string. When reading - read the number of bytes, allocate the necessary memory and already write to it.

    for (int i = 0; i < size; i++) {
        int len = strlen(st[i].nam);
        fwrite(&len,sizeof(len),1,fp);
        fwrite(st[i].nam, sizeof(char), len, fp);
        fwrite(&(st[i].count), sizeof(int), 1, fp);
    }

Reading:

      for (int i = 0; i < size; i++) {
            int len;
            fread(&len,sizeof(len),1,fp);
            st[i].nam = (char*)calloc(len+1);
            fread(st[i].nam, sizeof(char), len, fp);
            fread(&(st[i].count), sizeof(int), 1, fp);
        }

Within a single program, when all the pointers are in place and point to lines with allocated memory, an incorrect read can slip through. To really make sure that everything is correct, you need to write in one program, and read in another.

 1
Author: Mikhailo, 2020-10-15 10:14:16