I have data that I want saved into a file. After running the program for the second time (after writing the data i want) the data that was saved is read as random values (arbitrary numbers). I'm not sure if this is because of the dynamically allocated array I'm using or not. If someone can tell me why its not saving and printing the correct data?
Code:
#include <stdio.h>
#include <stdlib.h>
int length=4, width=4;
struct LandData
{
int type;
int height;
};
struct LandData* WritingData()
{
int i, j;
FILE *land;
struct LandData *arr = (struct LandData*)malloc(length* width* sizeof(struct LandData));
if((land=fopen("file.bin","rb"))==NULL)
{
perror("Can't open File");
}
if(!(fread(arr,sizeof(struct LandData),1,land)))
{
printf("Error file is empty!\n");
if((land = fopen("file.bin", "wb")) == NULL)
{
printf("Unable to open file!\n");
exit(1);
}else printf("Opened file successfully.\n");
for (i = 0; i < length ; i++){
for (j = 0; j < width; j++){
printf("choose height: ");
scanf("%d",&(arr + i*width + j)->height);
printf("Choose type: ");
scanf("%d",&(arr + i*width + j)->type);
fwrite(arr, sizeof(struct LandData), 1, land);
}
}
if(fclose(land)!=0)
{
perror("Error on file closing after writing");
exit(2);
}
}
return(arr);
}
void DisplayingMap(struct LandData *arr)
{
FILE* land;
if((land=fopen("file.bin","rb"))==NULL)
{
perror("Can't open File");
exit(1);
}
printf("\n ");
for (int i=0 ; i<width; i++)
printf("%d| ", i);
printf("\n");
while(fread(arr,sizeof(struct LandData),1,land))
{
for (int i = 0; i < length ; i++) {
printf(" %d| ", i);
for (int j = 0; j < width; j++)
printf(" %d ", (arr + i*width + j)->height);
printf("\n");
}
if(fclose(land)!=0)
{
perror("Error on file closing after reading");
exit(2);
}
}
}
int main()
{
struct LandData *arr = WritingData();
DisplayingMap(arr);
}