Hey guys,
I would like some help regarding saving or reading to or from a bin file.
I've read several online tutorials about file input/output, however it doesn't given specific information when applying it to both an array of structures. My knowledge of pointers is weak, as I constantly need to look over examples to get an idea of whats going on.
Heres my attempt:
#define PLANET_SIZE 10
/* Called from function */
save(planet_t writePlanet[], *totalSize); /* define as int* totalSize */
read(planet_t *writePlanet);
typedef struct{
char name[20];
}planet_t;
/* Save to file */
void save(planet_t writePlanet[], int totalSize){
FILE *outFile;
int count;
outFile = fopen("planet.bin", "wb");
if(outFile==NULL){
printf("\nFile error.");
}
else{
for(count = 0; count<PLANET_SIZE; count++){ /**/
fwrite( &writePlanet, sizeof(writePlanet), 1, outFile);
printf("\n%s", writePlanet[count].name); /* Test to see if its writing. */
}
fclose(outFile);
}
getchar();
}
/* Read from file */
void readFleet(planet_t *writePlanet){
FILE *inFile;
int count;
inFile = fopen("planet.bin", "rb");
if(inFile == NULL){
printf("\nFile error.");
}
else {
for(count = 0; count < PLANET_SIZE; count++){
fread(&writePlanet, sizeof(writePlanet), 1, inFile);
printf("\nPlanet name:\t%s", writePlanet[count].name);
}
}
fclose(inFile);
getchar();
}
My problem is that im not sure if its reading or saving properly.
I'm definitely sure its not reading from file properly.
Its an assignment and would prefer not to reveal any further code unless neccessary, however I am really stuck on this problem.
My first thought of a solution was to have another array of struct which would at the end of 'void read' copys value over to the original array of struct, however I think my problem lies when passing the array of struct to 'void read'.
Would appreciate any help or useful links.
Cheers,