1

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!

linuxie
  • 127
  • 3
  • 14
  • It's not true that there is no answer in the Internet. The problem is that you don't know how to combine the big amount of information that there is in the Internet. feof() doesn't work because you are in 'w' mode. – castarco Nov 03 '14 at 09:29
  • 2
    Regarding issue with `feof()`, you can read http://stackoverflow.com/q/5431941/1865106 – SSC Nov 03 '14 at 09:30
  • @SSC different problem – M.M Nov 03 '14 at 10:08

3 Answers3

4

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;
}
Community
  • 1
  • 1
David Ranieri
  • 39,972
  • 7
  • 52
  • 94
1

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.

Rohan
  • 52,392
  • 12
  • 90
  • 87
0

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

Neozaru
  • 1,109
  • 1
  • 10
  • 25