There is a sentence in a text file and I am trying to insert a word into 9. character in the text file. For example,if the sentence is "Los Angeles is a good city,Paris is a good city" , my program will insert the text "CHPBL" into 9. character,after this modification the sentence in the file1.txt will look like:
"Los AngeleCHPBLs is a good city,Paris is a good city"
I did a little program to do it:
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char buffer[6];
char buffer2[6];
char buffer3[6];
char word[6];
strcpy( word, "CHPBL" );
FILE* fp;
if ((fp = fopen( "file1.txt", "r+t" )) == NULL)
{
printf( "File error!" );
exit( EXIT_FAILURE );
}
fseek( fp, 9, SEEK_SET);
int counter=1;
int offset3 = ftell(fp);
fgets( buffer2, 6, fp);
fseek( fp, offset3, SEEK_SET);
fprintf( fp, "%s", word);
int offset = ftell(fp);
fgets( buffer, 6, fp);
int counter2=0;
while( !feof(fp) )
{
system( "pause" );
int offset2 = ftell(fp);
fseek( fp, offset2, SEEK_SET); //if I don't use this fseek
//program works wrong
//buffer3 takes wrong values
if ( fgets ( buffer3, 6, fp ) == NULL)
{
exit(0);
}
sayac++;
printf( "%d. while loop", counter2);
printf( "\nbuffer : %s \n ", buffer);
printf(" \nbuffer3 : %s \n ",buffer3);
if (counter==1)
{
fseek( fp, offset, SEEK_SET);
fprintf( fp, "%s", buffer2);
printf(" \nbuffer2 : %s \n", buffer2);
}
if (counter==0) fseek( fp, offset2, SEEK_SET);
fprintf(fp, "%s", buffer);
counter = 0;
strcpy( buffer, buffer3);
}
This code works as I want but there is something which I am not able to understand.If I don't use fseek there ( I commented it in the code) it works wrong and I do not understand why I must use fseek there.