hello, I am trying to write a program that makes 10 empty entries in my file, updating the first 3, and then asking the user which one to erase back to a blank entry, and then reprints the file contents again with the entry deleted. It seems to work okay ONLY if you delete the first entry, if you try to delete the 2nd or 3rd, the output goes all crazy! Any help would be greatly appreciated! :(
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
typedef struct person {
char first_name[15];
char last_name[15];
char age[4];
int accNum;
} Person;
int main(int argc, char * argv[])
{
FILE * file = fopen("/Users/MYNAME/Desktop/person.txt", "r+");
Person blankEntry = {"No First Name", "No Last Name", "0", 0};
Person person1 = blankEntry;
printf("Records:\n");
for(int i = 1; i <= 10; i++) {
fwrite(blankEntry.first_name, 1, sizeof(blankEntry.first_name), file);
fwrite(blankEntry.last_name, 1, sizeof(blankEntry.last_name), file);
fwrite(blankEntry.age, 1, sizeof(blankEntry.age), file);
fprintf(file, "%d", i);
printf("%d. %s\t\t\t%10s%10s\n", i, blankEntry.first_name, blankEntry.last_name, blankEntry.age);
}
printf("\n\nUpdating Record:\n");
fseek(file, SEEK_SET, 0);
for(int i = 1; i <= 3; i++) {
printf("Enter in first name, last name, and age: ");
scanf("%s %s %s", person1.first_name, person1.last_name, person1.age);
fwrite(person1.first_name, 1, sizeof(person1.first_name), file);
fwrite(person1.last_name, 1, sizeof(person1.last_name), file);
fwrite(person1.age, 1, sizeof(person1.age), file);
fprintf(file, "%d", i);
}
printf("\n\nRecords:\n");
printf("First Name:\t\tLast Name:\t\tAge:\n");
fseek(file, SEEK_SET, 0);
for(int i = 1; i <= 10; i++) {
fread(person1.first_name, 1, sizeof(person1.first_name), file);
fread(person1.last_name, 1, sizeof(person1.last_name), file);
fread(person1.age, 1, sizeof(person1.age), file);
fscanf(file, "%d", &person1.accNum);
printf("%i. %s\t\t%10s%10s\n", person1.accNum, person1.first_name, person1.last_name, person1.age);
}
int deleteKey;
printf("\n\nEnter in account number to delete: ");
scanf("%i", &deleteKey);
fseek(file, (deleteKey - 1) * sizeof(struct person), SEEK_SET);
fwrite(person1.first_name, 1, sizeof(person1.first_name), file);
fwrite(person1.last_name, 1, sizeof(person1.last_name), file);
fwrite(person1.age, 1, sizeof(person1.age), file);
//fwrite(&blankEntry, sizeof(struct person), 1, file);
printf("\n\nRecords:\n");
printf("First Name:\t\tLast Name:\t\tAge:\n");
fseek(file, SEEK_SET, 0);
for(int i = 1; i <= 10; i++) {
fread(person1.first_name, 1, sizeof(person1.first_name), file);
fread(person1.last_name, 1, sizeof(person1.last_name), file);
fread(person1.age, 1, sizeof(person1.age), file);
fscanf(file, "%d", &person1.accNum);
printf("%i. %s\t\t%10s%10s\n", person1.accNum, person1.first_name, person1.last_name, person1.age);
}
fclose(file);
return 0;
}