I am simply trying to get user input, store it in a struct, write it to a binary file, and then read it again. It is for the start of a contact book type program. When I try to retrieve the data for a single struct, it does not read into my readStruct and I get a seg fault at the marked comment in the code.
Also, please mind the messy use of dynamic strings and user input. I was just playing around and learning from it.
Thanks.
Heres the code:
int main(void) {
struct contactStruct {
int phoneNumber;
char * firstName;
char * lastName;
char * companyName;
};
struct contactStruct contact;
struct contactStruct read;
//Variable Declaration
int j = 1;
char tempInput[100] = "-";
char * menuInput;
char * searchInput;
bool menuLoop = false;
FILE * filePointer;
filePointer = fopen("contactList.db", "r+");
if (filePointer == NULL) {
filePointer = fopen("contactList.db", "w+");
}
printf("Welcome to the Contact Book Program\n");
printf("This program will let you store and access all of your contacts!\n");
do {
menuLoop = false;
printf("Would you like to: 'ADD', 'EDIT', 'VIEW', or 'REMOVE' a contact? - ");
fgets(tempInput, sizeof(tempInput), stdin);
for (int i = 0; i < strlen(tempInput); i++) {
tempInput[i] = tolower(tempInput[i]);
}
menuInput = malloc(sizeof(char) * strlen(tempInput) + 1);
strcpy(menuInput, tempInput);
if (strcmp(menuInput, "add\n") == 0) {
printf("Phone Number: ");
fgets(tempInput, sizeof(tempInput), stdin);
contact.phoneNumber = atoi(tempInput);
printf("First Name: ");
fgets(tempInput, sizeof(tempInput), stdin);
contact.firstName = malloc(sizeof(char) * strlen(tempInput) + 1);
strcpy(contact.firstName, tempInput);
printf("Last Name: ");
fgets(tempInput, sizeof(tempInput), stdin);
contact.lastName = malloc(sizeof(char) * strlen(tempInput) + 1);
strcpy(contact.lastName, tempInput);
printf("Company Name: ");
fgets(tempInput, sizeof(tempInput), stdin);
contact.companyName = malloc(sizeof(char) * strlen(tempInput) + 1);
strcpy(contact.companyName, tempInput);
fwrite( & contact, sizeof(struct contactStruct), 1, filePointer);
} else if (strcmp(menuInput, "view\n") == 0) {
printf("Who are you searching for? (First Name): ");
scanf("%s", tempInput);
searchInput = malloc(sizeof(char) * strlen(tempInput) + 1);
strcpy(searchInput, tempInput); // Get name being searched for
fread( & read, sizeof(struct contactStruct), 1, filePointer);
printf("DEBUG - File Pos: %ld Size of Struct: %lu\n", ftell(filePointer), sizeof(struct contactStruct));
printf("Input: %s Searching: %s\n", searchInput, read.firstName); //Seg Fault Happens Here
if (strcmp(searchInput, read.firstName) == 0) {
printf("Here is the contact information given:\n\n");
printf("%d %s %s %s \n", read.phoneNumber, read.firstName, read.lastName, read.companyName);
} else {
printf("Did not find\n");
}
} else {
printf("Invalid Option, Try Again.\n");
menuLoop = true;
}
}
while (menuLoop == true);
free(menuInput);
free(searchInput);
fclose(filePointer);
return 0;
}