Recentl I have started learning file I/O in C like fopen fwrite and stuff like that. I have a question regard writing/reading a struct that has pointers to a file. Let's say the struct looks like this
struct {
int len;
int* data;
}intarr;
len is the length of the array
data points to a integer array.
Assuming I know what the struct is(so I can read it back later on), I need to write len and data into the file in binary format. But if I only write the struct to the file, only the pointers are saved into the file instead of the content.
My current approach is that I copy the data into a new array,then I write the len and the new array into the file separately.
I am not too sure if my approach is correct or not. If it is correct, how are you supposed to read them back? If not ,what are we supposed to do when we want to write all the content of a struct with pointers into a file so we can read them back later?...
I am still new to programming so if I have said anything wrong,please correct me.
Copyright Notice:Content Author:「GalaxyVintage」,Reproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/28936092/writing-and-reading-into-a-file-in-c-language