Here is my function for updating strings in a file, in order to change a certain task you have to key in the unique idnumber and itll then print out the line and you can change the variables For example, my file contains: 02 AnnesBirthday 17 12 2022 Event 03 JacksBirthday 12 12 2022 Event
so if u key in in the scanf 02 itll print out: AnnesBirthday 17 12 2022 Event and you can change these data but the issue im having is that after changing this data the rest of the strings in the file is gone so for example i changed id 02, id03 goes missing it gets completely erased
void UpdateTask() {
char taskname[100];
int i,idnumber,date, month, year, choice;
char category[20];
FILE *f = fopen("tasks.txt", "r");
FILE *ft = fopen("temp.txt", "w");
printf("\n********");
printf("\nUpdate tasks here");
printf("\n********");
printf("\nEnter task number: ");
scanf("%d", &i);
while (fscanf(f, "%d", &idnumber) != EOF) {
fscanf(f,"%d %s %d %d %d %s\n",idnumber,taskname, date, month, year, category);
if (i == idnumber) {
printf("\nUpdating -> %s %d %d %d %s", taskname, date, month, year, category);
printf("\nEnter a new task name: ");
fflush(stdin);
gets(taskname);
printf("\nEnter a new day (dd/mm/yy): ");
scanf("%d",&date);
printf("\nEnter a new month (dd/mm/yy): ");
scanf("%d",&month);
printf("\nEnter a new year(dd/mm/yy): ");
scanf("%d",&year);
printf("\nEnter a new category (max 49 characters): ");
fflush(stdin);
gets(category);
fprintf(ft, "%d %s %d %d %d %s\n", idnumber, taskname, date, month, year,
category);
fclose(ft);
fclose(f);
remove("tasks.txt");
rename("temp.txt", "tasks.txt");
}
else
fprintf(ft, "%d%s", i,taskname, date, month, year, category );
}
CodePudding user response:
That's because you close the file right after you print the modified line.
All the code
fclose(ft);
fclose(f);
remove("tasks.txt");
rename("temp.txt", "tasks.txt");
must be moved outside of the loop.
CodePudding user response:
Most likely you are getting data removed from your records is in the format of the "fprint" statement following the "else" statement.
fprintf(ft, "%d%s", i,taskname, date, month, year, category );
That statement should probably be:
fprintf(ft, "%d %s %d %d %d %s\n", idnumber, taskname, date, month, year, category);
Also, you should move those close, remove, and rename statements outside your loop as recommended in the previous answer.
Hope that helps.
Regards.