Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

C Basic language Im wrinting a code that creates a \"to-do\" list, and one of th

ID: 3824939 • Letter: C

Question

C Basic language

Im wrinting a code that creates a "to-do" list, and one of the things i need to do for it is to be able to edit entries that i have already read to my file. So i need to search for the string that is in the file and have the user enter a new string that gets put in the same spot that the string that we are replacing was found. Below is my editEntry() function that im trying to search for the line ('opt' correspond to the line in the file that needs editing). Then asking the user to enter in the new description and puts that in the empty line that is in the file. Do i need to use binary searching to find the line? Any help is welcome.

void editEntry() {
   char change[100];
   char newEntry[100];
   int opt;
   printf("Enter entry number to edit (1..%d; 0 to cancel)", a);
   scanf("%d", &opt);
   flist = fopen("mylist.txt", "r+");
   int i = 0;
   for (i = 0; i < opt; i++) {
       fgets(change, 100, (FILE*)flist);
   }

           printf("Enter a new description (empty to cancel):");
           fgets(newEntry, 100, (FILE*)flist);
           fputs(newEntry, (FILE*)flist);
      
   fclose(flist);
};

Explanation / Answer

Lets break your question statement

i need to do for it is to be able to edit entries that i have already read to my file.

So i need to search for the string that is in the file

Your code is not searching for string but looping till line number provided by user. (Is this what you want)

and have the user enter a new string that gets put in the same spot that the string that we are replacing was found.

This is being done incorrectly. You need to stop one line before your line number otherwise you will be overwriting next line.

Do i need to use binary searching to find the line?

Lets assume you want to actually search for a line and not line number.

In that case also as file is to be read, it will not give you any benefit.

Also binary search works only for sorted output.

So my advice, if you want to use line number, your code seems good with minor change mentioned earlier.

If you actually want to take user input, loop through completefile, and compare each read string with usr provided string using strcmp and break loop when it returns 0. Also note you need to seek back one line to write.