I have an elf file that called example. I wrote following code which it’s read the content of the example file in the binary mode and then I wanted to save their content in another file called example.binary. But when I run the following program it shows me a segmentation fault. What’s wrong with this program? I can’t find out my mistake.
#include <stdio.h> #include <stdlib.h> #include <string.h> // typedef macro typedef char* __string; //Function prototypes void readFileToMachine(__string arg_path); int main(int argc, char *argv[]) { __string pathBinaryFile; if(argc != 2){ printf("Usage : ./program file.n"); exit(1); } pathBinaryFile = argv[1]; readFileToMachine(pathBinaryFile); return EXIT_SUCCESS; } void readFileToMachine(__string arg_path){ int ch; __string pathInputFile = arg_path; __string pathOutputFile = strcat(pathInputFile, ".binary"); FILE *inputFile = fopen(pathInputFile, "rb"); FILE *outputFile = fopen(pathOutputFile, "wb"); ch = getc(inputFile); while (ch != EOF){ fprintf(outputFile, "%x" , ch); ch = getc(inputFile); } fclose(inputFile); fclose(outputFile); }
Advertisement
Answer
change your typedef to typedef char* __charptr
void rw_binaryfile(__charptr arg_path){ FILE *inputFile; FILE *outputFile; __charptr extension = ".binary"; __charptr pathOutputFile = strdup(arg_path); if (pathOutputFile != NULL){ pathOutputFile = realloc(pathOutputFile, strlen(arg_path) + sizeof(extension)); if (pathOutputFile != NULL){ pathOutputFile = strcat(pathOutputFile, ".binary"); inputFile = fopen(arg_path, "rb"); outputFile = fopen(pathOutputFile, "wb"); write_file(inputFile, outputFile); } } } void write_file(FILE *read, FILE *write){ int ch; ch = getc(read); while (ch != EOF){ fprintf(write, "%x" , ch); ch = getc(read); } }