I want to check if my predefined data is in the .dat file that I have. If it so, I print them. If not, my program crashes because the function I wrote has nothing to return.
How do I fix this? How can I check if there is no match and say "No match" and prevent my program being crashed?
struct objectList is for my predefined data. struct database is for the data in .dat file.
struct objectList
{
double oArea;
double oLength;
double oFormFactor;
};
struct database
{
char name[15];
double dArea;
double dLength;
double dFormFactor;
};
This function reads the file and returns the value if only "area", "length" and "formFactor" matches.
struct database myReadFile(FILE *rPtr, double area, double length, double formFactor)
{
struct database fromDb = { "", 0.0, 0.0, 0.0 };
if ((rPtr = fopen("objects.dat", "r")) == NULL)
printf("Couldn't open the file to read.\n");
else
{
fscanf(rPtr, "%s%lf%lf%lf", fromDb.name, &fromDb.dArea, &fromDb.dLength, &fromDb.dFormFactor);
while (!feof(rPtr))
{
if (fromDb.dArea == area)
if (fromDb.dLength == length)
if (fromDb.dFormFactor == formFactor)
{
printf("We have found the %s\n", fromDb.name);
return fromDb;
}
fscanf(rPtr, "%s%lf%lf%lf", fromDb.name, &fromDb.dArea, &fromDb.dLength, &fromDb.dFormFactor);
}
}
fclose(rPtr);
}
This function prints the values.
void getValues(FILE *gPtr, double area, double length, double formFactor)
{
struct database objectValues = { "", 0.0, 0.0, 0.0 };
objectValues = myReadFile(gPtr, area, length, formFactor);
printf("Object name: %s\n", objectValues.name);
printf("Object area: %.2lf\n", objectValues.dArea);
printf("Object length: %.2lf\n", objectValues.dLength);
printf("Object formFactor: %.2lf\n", objectValues.dFormFactor);
}
main:
int main()
{
struct objectList myObjectList[4];
myObjectList[0] = { 9214.00, 417.24, 22.08 }; // Coin
myObjectList[1] = { 54375.00, 1087.94, 49.97 }; // mp3
myObjectList[2] = { 12785.00, 550.70, 23.22 }; // toy
myObjectList[3] = { 100.01, 200.02, 300.03 }; // Random stuff
FILE *cfPtr;
if ((cfPtr = fopen("objects.dat", "a +")) == NULL)
printf("Couldn't open the file\n");
else
fclose(cfPtr);
int i = 2;
getValues(cfPtr, myObjectList[i].oArea, myObjectList[i].oLength, myObjectList[i].oFormFactor);
return 0;
}
My .dat file has "toy", "coin", "mp3" but not "random stuff". So when i = 3, my program crashes.