Is it possible to write an entire struct to a file
Your question is actually writing struct instances into file.
- You can use
fwrite
function to achieve this.
- You need to pass the reference in first argument.
sizeof
each object in the second argument
- Number of such objects to write in 3rd argument.
- File pointer in 4th argument.
- Don't forget to open the file in
binary mode
.
- You can read objects from file using fread.
Careful with endianness when you are writing/reading in little endian systems and reading/writing in big endian systems and viceversa. Read how-to-write-endian-agnostic-c-c-code
struct date *object=malloc(sizeof(struct date));
strcpy(object->day,"Good day");
object->month=6;
object->year=2013;
FILE * file= fopen("output", "wb");
if (file != NULL) {
fwrite(object, sizeof(struct date), 1, file);
fclose(file);
}
You can read them in the same way....using fread
struct date *object2=malloc(sizeof(struct date));
FILE * file= fopen("output", "rb");
if (file != NULL) {
fread(object2, sizeof(struct date), 1, file);
fclose(file);
}
printf("%s/%d/%d\n",object2->day,object2->month,object2->year);