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

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.