Skip to content

Instantly share code, notes, and snippets.

@chaomai
Created October 26, 2016 14:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chaomai/72cfca84763e15cec951097711ee6d5a to your computer and use it in GitHub Desktop.
Save chaomai/72cfca84763e15cec951097711ee6d5a to your computer and use it in GitHub Desktop.
read file as binary format
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[]) {
if (argc != 2) {
printf("%s\n", "wrong number of parameters");
exit(-1);
}
FILE *file_ptr = fopen(argv[1], "rb");
fseek(file_ptr, 0, SEEK_END);
long file_size = ftell(file_ptr);
rewind(file_ptr);
char *file_content = (char *)malloc(file_size);
if (file_content == NULL) {
printf("%s\n", "fail to malloc");
exit(-1);
}
fread(file_content, 1, file_size, file_ptr);
char *ret_file_name = (char *)malloc(strlen(argv[1]) + 4);
strcpy(ret_file_name, argv[1]);
strcat(ret_file_name, "_ret");
FILE *ret_file_ptr = fopen(ret_file_name, "wb");
fwrite(file_content, 1, file_size, ret_file_ptr);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment