user3646905 user3646905 - 6 months ago 18
Linux Question

Reading 2 byte at a time from a binary file

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

}

LPs LPs
Answer

You have no room to concatenate extention to path so you have to create space for that.

One solution could be:

char ext[] = ".binary";
pathOutputFile = strdup(arg_path);
if (pathOutputFile != NULL)
{
   pathOutputFile = realloc(pathOutputFile, strlen(arg_path) + sizeof(ext));
   if (pathOutputFile != NULL)
   {
       pathOutputFile = strcat(pathInputFile, ".binary");


      // YOUR STUFF
   }

   free(pathOutputFile);
}

Side note: typedef a pointer is not a good idea...