0

Hello guys,

How can I read and write in the same file? I want to open a file that exists and write something in the end of each line of the file..

Ex:
My_file:
a b c
d e f
g h i

I want to alter to:
a b c XX
d e f XX
g h i XX

I tried this but the file does not altered..

#include <stdio.h>
#include <stdlib.h>

int main()
{
  FILE *f;
  f  = fopen("file.txt", "a+");

  while  (fgets(line,sizeof(line),f)){
       fputc("XX",f);
   }

  fclose(f);
  return 0;
}

I tried a lot of thing like open in other modes, and nothing

thanks

2
Contributors
1
Reply
2
Views
9 Years
Discussion Span
Last Post by Salem
0

Well since the file is stored as
a b c\nd e f

What's going to happen to the 2nd line when you add XX to the first?

There is no "insert" function for a file.

Unless you're replacing N bytes with N bytes, you need to read from one file, and write to another.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.