4

I need to add a string before the 45th byte in an existing file. I tried using fseek as shown below.

int main()
{
    FILE *fp;
    char str[] = "test";     

    fp = fopen(FILEPATH,"a");
    fseek(fp,-45, SEEK_END);                
    fprintf(fp,"%s",str);
    fclose(fp);     
    return(0);
}

I expected that this code will add "test" before the 45th char from EOF, instead, it just appends "test" to the EOF.

Please help me to find the solution.

This is continuation of my previous question
Append item to a file before last line in c

2
  • which previous question? Could you please link to it? Jul 16, 2010 at 11:50
  • Thanks alexandre and Brian. I got the solution below.
    – arun
    Jul 16, 2010 at 12:24

3 Answers 3

11

Open it with mode r+ (if it already exists) or a+ (if it doesn't exist and you want to create it). Since you're seeking to 45 bytes before the end of file, I'm assuming it already exists.

fp = fopen(FILEPATH,"r+");

The rest of your code is fine. Also note that this will not insert the text, but will overwrite whatever is currently at that position in the file.

ie, if your file looks like this:

xxxxxxxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxxxxxx

Then after running this code, it will look like this:

xxxxxxxtestxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxxxxxx

If you really want to insert and not overwrite, then you need to read all the text from SEEK_END-45 to EOF into memory, write test and then write the text back

0
3

Don't open it as append (a) if you plan to write at arbitrary positions; it will force all writes to the end of the file. You can use r+ to read or write anywhere.

0
0

To avoid platform-specific configurations, always explicitely indicate the binary or text mode in your fopen() call.

This will save you hours of desperations if you port your code one day.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.