I am trying to save a struct (listed)
typedef struct tupleStruct{
int element[eMax];
char * id;
int eCount;
}tuple_t;
typedef struct {
tuple_t * array;
int used;
int size;
} DynamicArray;
As part of an assignment I was instructed to save tuples that are stored in a dynamic array in a file. Unfortunately since strings don't exist in c (at least not like they do in other languages). Whenever I try to save an element of the dynamic array in a file, the string is not stored or loaded properly as it's seen as a pointer. I've even tried by initializing it like so in the struct:
char id[256];
Is there any way possible to save the struct and the string in a single file? (Given that I need to store multiple of these)
Edit: Saving and loading code
Loading
DynamicArray loadAllTuples(){
FILE *filePointer;
DynamicArray tempArray;
if((filePointer=fopen("SavedTuples.bin","rb"))==NULL)
{
fputs("Something went wrong while loading!\nA blank Array will be loaded instead\n", stderr);
setbuf(stdout, 0);
//In case of error, blank array is initalised and loaded
fclose(filePointer);
intialiseDynamicArray(&tempArray);
return tempArray;
}
fread(&tempArray, sizeof(DynamicArray),1,filePointer);
//Freeing filePointer memory
free(filePointer);
return tempArray;
}
saving
void saveAllTuples(DynamicArray ToSave){
trimArray(&ToSave,0); //Removing extra space from array
FILE * filePointer;
if((filePointer=fopen("SavedTuples.bin","wb"))==NULL)
{
fputs("Something went wrong while saving!\n", stderr);
setbuf(stdout, 0);
return;
}
fwrite(&ToSave, sizeof(ToSave), 1,filePointer);
fclose(filePointer);
}
called by
saveAllTuples(dynaArray);
and
dynaArray=loadAllTuples();
fprintfto write a string to a file. It works just likeprintfexcept the first argument is aFILE*char *) to file: stackoverflow.com/questions/4182876/… . After that, you still need to write theelementarray andeCount. Should you write the size ofelementtoo so that's recoverable, or is that fixed/able to be deduced from the data? You'll also need to writeusedandsizefrom theDynamicArray. You'll need to write it all in a specific way such that the reader knows the format and can recover all the data exactly.