Currently doing C programming homework, I want to update the value in the file. But now I'm having a problem updating it. The problem I faced now was the codes below update the values but in the form of new lines. Instead of replace the original lines. What's wrong with my codes ?

FILE* phoneFile;
int position_in_file,newStock;

printf("Enter new stock: ");

position_in_file = ftell(phoneFile);
fprintf(phoneFile,"%s %s %d %d %d\n",mobile[i].mCode,mobile[i].mName,

If you want to replace an existing line then you need another temp file. You can't just simply replace an existing line in a text file because the length of the old and new lines may not be the same. If you attempt to do it anyway you will wind up with barbage in the line following the one you replace.

First, open the original file for reading and open a temp file for writing.

  • read a line from the original file
  • if the line is the one you want to replace then write the new line to temp file
  • otherwise if the line does not need to be replaced then write it to the temp file
  • repeat the above until the entire original file has been read
  • close both files
  • delete the original file
  • rename temp file to the same name as original file

What AD says is correct; however, if the file is small enough to fit into memory, then you can read the file into an array of char pointers (one per line), modify the appropriate line, and then write the data back to the file (truncating the file if the output is smaller than the input). On modern systems, this will work nicely (and more efficiently than the temp file solution) for files up to about 1GB in size. Bigger than that, go the temp file route.