I can write to binary file and read it on the same execution. But if I execute the program later just to read from the file, it results in seg fault. I have hard-coded everything and omitted error checking for the sake of simplicity of question.
#include <stdio.h>
#include <stdlib.h>
typedef struct Details {
int num;
char *name;
}details;
int writeData(char *, details *);
int readData(chhar *);
int main() {
details *new;
new = (details *)malloc(sizeof(new));
new->num = 8;
new->name = "Name";
writeData("filename", new);
readData("filename"); //no error on this instance
}
int writeData(char *name, details *new) {
FILE *fp;
fp = fopen(name, "wb+");
fwrite(&new, sizeof(new), 1, fp);
fclose(fp);
}
int readData(char *name) {
details *new;
FILE *fp;
fp = fopen(name, "rb");
fread(&new, sizeof(new),1,fp);
printf("%d\n", new->num);
printf("%s\n", new->name);
fclose(fp);
}
But if I
//writeData("filename", new);
and compile again and run with only
readData("filename");
then it results in seg fault. I've tried everything in my knowledge. What I am unable to understand is that file-to-be-read exists, it should not matter whether I recompile the code or not.
Reading and writing pointers is useless. write
will not write a pointed-to object, read
will not magically allocate memory for you and read the pointed-to object.
Since the type you want to store itself contains a pointer, reading and writing it directly won't work either. Only structs without any pointers in them can be read and written safely.
That is, if your struct were like this
typedef struct Details {
int num;
char name[SOME_SIZE];
} details;
you would be able to read and write it like this
fwrite(new, sizeof(*new), 1, fp);
new = malloc(sizeof(*new));
fread(new, sizeof(*new), 1, fp);
but the char*
member means this simple method will fail.
You need to write a serialisation and deserialisation functions for your data type, and use them to read and write objects of that type.
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.