1

I am trying to use this code, except instead of overwriting the file I want to just append it. However, when I use the mode "a" or "a+", the fseek seems to not work. Instead of writing to the file "This is C Programming Langauge", as expected, it writes "This is tutorialspoint.com C Programming Langauge". What can I do to not overwrite the file?

I want to be able to open a file with text already in it, set the file pointer to a certain point, and write text to that point without overwritign anything else in the file.

int main ()
{
  FILE *fp;

  fp = fopen("file.txt","w+");
  fputs("This is tutorialspoint.com", fp);

  fseek( fp, 7, SEEK_SET );
  fputs(" C Programming Langauge", fp);
  fclose(fp);

  return(0);
}
mh234
  • 37
  • 6
  • 3
    possible duplicate of [fseek does not work when file is opened in "a" (append) mode](http://stackoverflow.com/questions/10631862/fseek-does-not-work-when-file-is-opened-in-a-append-mode) – Thomas Sep 21 '14 at 21:26

1 Answers1

3

You incorrectly believe fseek() is not working, when it IS working. The problem is that when you open a file for "append", as in fopen("file.txt", "a+");, then all writes will be appended to the end of the file, regardless of the location of the file pointer. So, what happens is fseek() correctly repositions the file pointer to 7, but as soon as you call fputs() again, the file pointer is positioned to the end of the file before the output takes place.

Here is an example which reads from file.txt after the fseek() to show it is positioned where you'd expect:

#include <stdio.h>

int main ()
{
   FILE *fp;
   char buffer[100];

   fp = fopen("file.txt","a+");
   fputs("This is tutorialspoint.com", fp);

   fseek( fp, 7, SEEK_SET );
   fgets(buffer, sizeof(buffer), fp);
   printf("Buffer-->%s<--\n", buffer);
   fseek( fp, 7, SEEK_SET );
   fputs(" C Programming Langauge", fp);
   fclose(fp);

   return(0);
}
TonyB
  • 927
  • 6
  • 13