user3408660
user3408660

Reputation: 83

How to edit one line in txt file in C?

I'm trying to edit the first line in a txt file, but for some reason it will replace the next line with whitespace character...

int main()
{
  FILE *myFile;
  myFile = fopen("test.txt", "r+");
  fprintf(myFile, "Hello\n");
  fclose(myFile);
}

txt file before run code:

i
like
this

txt file after run code:

Hello

this

Upvotes: 1

Views: 110

Answers (1)

user1864610
user1864610

Reputation:

Your code hasn't replaced lines, it's replaced bytes. Your string ("Hello\n") is six bytes long. The first six bytes of your file are "I\nlike". Once your code has executed you have "Hello\n\nthis" - i.e 'Hello', two newlines and 'this'.

If you're trying to replace just the first line you will need to read the entire file, parse it for lines, replace the line you want to replace, then write out the new content.

Upvotes: 7

Related Questions