For school (voluntary, not a required project), I'm creating a bonuscalc for the teachers to use. Everything is coming along smoothly, except for a portion of code that handles whether or not a file is present.
The function is called 'isFoundDb' and is of type 'int'. It returns a value to main depending on whether or not the file is found, and whether or not the user chooses to use the default values in the absence of that file. If the file is found, return 1. If not found, AND the user chooses not to use the file (which is a sort of database), return 0. If the user wants to use the file, return -1.
The program is split up into one file per function. 'Main.c' includes 'isFoundDb.c' and the .h file holding all the functions I have prototyped. Therefore, each .c file defines the functions in the .h file.
isFoundDb.c:
Code:
#include <stdio.h>
#include <conio.h>
#include "bonusCalc.h"
int isFoundDb() {
char choice = -1;
int cdn = -2;
int i = 0;
FILE *database;
database = fopen("DATABASE.TXT","r");
if (database == NULL) {
printf("WARNING: \n");
printf("Database file not found!\n");
printf("Did you copy over the BIN folder?\n");
printf("Default bonuses will be used.\n");
do {
printf("Is that okay? (y/n): ");
fflush(stdin);
choice = getch();
switch(tolower(choice)) {
case 'y':
cdn = 0;
break;
case 'n':
cdn = -1;
break;
default: printf("That isn't a valid choice\n");
}
if (cdn >= 0) {
i = 1;
}
else {
i = 0;
}
} while (i = 0);
}
else if (database != NULL) {
cdn = 1;
}
else {
cdn = -2;
}
return cdn;
}
Main.c:
Code:
#include <stdio.h>
#include "bonusCalc.h"
#include "isFoundDb.c"
int main(int argc, char *argv[]) {
int done = 0; /* Ensure that the following process isn't complete */
int quit = 0; /* Should the program quit? */
/* Check to make sure database.txt is present in the Bin folder
* If isFoundDb returns 0, don't use db
* If isFoundDb returns 1, use db
* If isFoundDb returns -1, the file is missing and the user must locate the file */
do {
if (isFoundDb() == 0) {
printf("\nUsing default values!\n");
done = 1;
}
else if (isFoundDb() == 1) {
printf("\nUsing database values!\n");
done = 1;
}
else if (isFoundDb() == -1) {
printf("\nDatabase.txt missing!\n");
quit = 1;
done = 1;
}
else {
printf("Unknown error!\n");
}
} while (done != 1);
return 0;
}
BonusCalc.h:
Code:
#ifndef bonusCalc_h
#define bonusCalc_h
int isFoundDb();
#endif
The code works perfectly except for when the user types 'n' in which case it repeats from the if (database == NULL) portion of code... which I don't understand. I'd have thought it would repeat from the embedded do while loop for some obscure reason. But what is perplexing is that if the user types 'y' it works fine. I'm at a loss.
Any help would be appreciated
PS: I tried using goto and even removing the do while loop but nothing's working.