linuxie
linuxie

Reputation: 127

How to overwrite a file in C?

My question is very simple. I have a file of ascii or binary , whatever. Now, I want every byte in the file to be 0x4f, how can I do it in C ? The question is so simple, but suprisingly, there is no answer on the Internet. I have a sample code, however, there is a dead loop when I run the program:

#include <stdio.h>
int main ()
{
    FILE * pFile;
    pFile = fopen ("write_file_2","wb");
    unsigned char c = 0x4f;
    while(1){
        if( feof(pFile) )
            break;
        int res = fputc(c, pFile);
        printf("%d\n", res);
    }
    fclose (pFile);
    return 0;
}

I wonder why the feof() takes no effect. Thanks!

Upvotes: 1

Views: 9150

Answers (3)

Rohan
Rohan

Reputation: 53316

As soon as you do this pFile = fopen ("write_file_2","wb"); the file is opened and truncated to 0 bytes. So the pFile is at EOF so feof() will return true.

You may want to open it with "r+b", get the size using ftell(), fseek() to 0th position and start writing design data.

Upvotes: 1

David Ranieri
David Ranieri

Reputation: 41017

The problem is that you are using "wb" (w - Create an empty file for output operations), change to "rb+", and use ftell instead of feof (take a look to “while( !feof( file ) )” is always wrong)

#include <stdio.h>

int main(void)
{
    FILE * pFile;
    long i, size;
    unsigned char c = 0x4f;

    pFile = fopen("write_file_2", "rb+");
    fseek(pFile, 0, SEEK_END);
    size = ftell(pFile);
    fseek(pFile, 0, SEEK_SET);
    for (i = 0; i < size; i++) {
        int res = fputc(c, pFile);
        printf("%d\n", res);
    }
    fclose(pFile);
    return 0;
}

Upvotes: 4

Neozaru
Neozaru

Reputation: 1130

Maybe you should firstly check the size of the file :

fseek(f, 0, SEEK_END);
lSize = ftell(f);
fseek(f, 0, SEEK_SET);

Then use 'fwrite' to write desired bytes and number of bytes into the file

Upvotes: 0

Related Questions