Saturday, 15 August 2015

fwrite - How to overwrite a file in C? -



fwrite - How to overwrite a file in C? -

my question simple. have file of ascii or binary , whatever. now, want every byte in file 0x4f, how can in c ? question simple, suprisingly, there no reply on internet. have sample code, however, there dead loop when run 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); homecoming 0; }

i wonder why feof() takes no effect. thanks!

the problem using "wb" (w - create empty file output operations), alter "rb+", , utilize ftell instead of feof (take “while( !feof( file ) )” 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); (i = 0; < size; i++) { int res = fputc(c, pfile); printf("%d\n", res); } fclose(pfile); homecoming 0; }

c fwrite

No comments:

Post a Comment