简体   繁体   中英

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, ...

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM