This is the struct definition that I am trying to write copies of to and read from binary file
typedef struct carType Car;
struct carType {
int vehicleID;
char make[20];
char model[20];
int year;
int mileage;
double cost;
Car *next;
};
This is my code for writing to a binary file(state of the Car)
void writeBinFile(Car *headPointer)
{
char fileName[20];
//prompt user for name of textfile to print to
scanf("%s", fileName);
FILE *ftp;
Car *start = headPointer->next;
ftp = fopen(fileName, "wb");
char separator = '0';
while(start != NULL)
{
//write out 1 cell of data, cell contains 4 bytes
fwrite(&start->year,sizeof(int), 1, ftp);
fwrite(start->make,sizeof(char), strlen(start->make), ftp);
fwrite(&separator, sizeof(char), 1, ftp);
fwrite(start->model, sizeof(char), strlen(start->make), ftp);
fwrite(&separator, sizeof(char), 1, ftp);
fwrite(&start->cost, sizeof(float), 1, ftp);
fwrite(&start->mileage, sizeof(float),1,ftp);
fwrite(&start->vehicleID, sizeof(int), 1, ftp);
start = start->next;
}
fclose(ftp);
}
This is my code for reading from a binary file(to state of the car)
void readFromBinFile(Car *headPointer)
{
char fileName[20];
//prompt user for name of textfile to print to
scanf("%s", fileName);
FILE *ftp;
Car *previous = headPointer;
ftp = fopen(fileName, "rb");
Car *current;
//go until the end of file is reached
while(!feof(ftp))
{
current = (Car *)malloc(sizeof(Car));
previous->next = current;
//program receives 1 cell, that cell contains 4 bytes
fread(¤t->year, sizeof(int),1,ftp);
printf("%d\n",current->year);
char make[25];
int count = 0;
char oneAtATime= 'a';
while(oneAtATime != '0')
{
fread(&oneAtATime, sizeof(char),1,ftp);
if(oneAtATime!='0')
{
make[count] = oneAtATime;
count++;
}
}
make[count] = 0;
strcpy(current->make, make);
char model[25];
count = 0;
oneAtATime= 'a';
while(oneAtATime != '0')
{
fread(&oneAtATime, sizeof(char),1,ftp);
if(oneAtATime!='0')
{
model[count] = oneAtATime;
count++;
}
}
model[count] = 0;
strcpy(current->model, model);
fread(¤t->cost, sizeof(float),1, ftp);
fread(¤t->mileage, sizeof(int),1,ftp);
fread(¤t->vehicleID, sizeof(int),1,ftp);
previous = previous->next;
}
fclose(ftp);
}
Last time I got a segmentation error from not allocating memory to the new car Why am I getting a segmentation failure?. I made sure to do that this time. I checked this one Segmentation fault when reading a binary file into a structure and Segmentation fault while reading binary file in C but my fields were values , not pointers. Does anyone see a glaring issue? I can't test anything bc whenever i try to run this, i get that error. The problem seems to be the reading but i am not sure if some code in the writing is causing the reading to fail