Search code examples
cpointersfwrite

Read/Write to file using void pointers in C


As part of a college assignment, I'm trying to do a simple C app, using Win32 for GUI programming and writing my own dynamic linked list for storing data. Since i could use it for other things later, I'm trying to write a generic list, with "built in" functions for reading and writing data to a file. Now here's my problem

 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>

 typedef struct tagA{
     int t_int;
     float t_float;
     char t_char;
     char t_vchar[30];
 } A;

 typedef struct tagB{
     void *data;
     struct tagB *prox;
 } B;

 int main(){
     A dA = {1, 1.5, 'a', "teste123"};
     B dB = {&dA, NULL};
     dB.data = &dA;
     B dB2 = {0};

     FILE *fp;
     fp = fopen("Data.txt", "w");

     size_t dSize = sizeof(dA);
     printf("Struct size: %d", dSize);

     if(fp == NULL){
         printf("nope");
     }else{
         fwrite(&dB.data, dSize, 1, fp);
     }
     fclose(fp);
     fp = fopen("Data.txt", "r");

     dB2.data = malloc(dSize);
     fread(&dB2.data, dSize, 1, fp);

     printf("\n\n%s", ((A*)dB2.data)->t_vchar);
 }

This is the code I'm trying to work out.

  • The writing works just fine, and I just have to make it to a separate function that receives the pointer to the data struct and its size.
  • But the reading is off... Once read and printed to the console, the t_int shows a really large number, the t_float has nothing, and so the char and string...

Also, I know its not the best written, most efficient and safe code, but it's just a prototype, something that came into my mind...


Solution

  • Your problem is you are writing the address of &dB.data with fwrite instead of dB.data itself (it is already a pointer). For example:

    fwrite(dB.data, dSize, 1, fp);
    

    will resolve your problem (with the like corresponding change to fread).