Goldenbough
Goldenbough

Reputation: 93

Reading and writing binary file in C language

I tried to read and write fild in C but it failed. It partly worked, but the original file and the output file is not same. I tried to read and write bmp file.

FILE* openFile = fopen(argv[1], "rb");                      
FILE* writeFile = fopen(strcat(argv[1], ".cpd"), "wb");     
fseek(openFile, 0, SEEK_END);                               
long size = ftell(openFile);                                
char* bin = (char*)malloc(sizeof(char) * (size + 1));       
rewind(openFile);                                           
fwrite(bin, size, 1, writeFile);

//closefile, free, ...

Upvotes: 0

Views: 80

Answers (1)

lenik
lenik

Reputation: 23556

You should add reading the original file somewhere in your code:

FILE* openFile = fopen(argv[1], "rb");                      
FILE* writeFile = fopen(strcat(argv[1], ".cpd"), "wb");     
fseek(openFile, 0, SEEK_END);                               
long size = ftell(openFile);                                
char* bin = (char*)malloc(sizeof(char) * (size + 1));       
rewind(openFile);                                           
fread(bin, size, 1, openFile);   // <-- here, for example
fwrite(bin, size, 1, writeFile);

Upvotes: 1

Related Questions