I can't seem to find the reason of why I'm getting the segmentation fault in my code. The moment my code starts to write the bytes of buffer, I encounter the fault
Any help is really appreciated.
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char* argv[])
{
// argc check
if(argc != 2)
{
fprintf(stderr, "Invalid argument count. It should be ./recover card.raw\n");
return 1;
}
// open input file
FILE *input = fopen(argv[1], "r");
if(input == NULL)
{
fprintf(stderr, "Couldn't open the file.\n");
return 4;
}
// allocate 512B memory
int *buffer = malloc(512);
if (buffer == NULL)
{
fclose(input);
fprintf(stderr,"Cannot create a buffer.\n");
return 3;
}
// read the card.raw, while checking the EOF
while(fread(buffer, 512, 1, input) == 1)
{
// print the first 4 bytes
printf("%#x\n",buffer[0]);
//check the first 4 bytes for .jpeg
if((buffer[0] & 0xf0ffd8ff) == 0xe0ffd8ff)
{
// create a new file
char c[3];
int i = 0;
sprintf(c, "%03i.jpg", i);
FILE *image = fopen(c, "w");
if (image == NULL)
{
fclose(input);
fprintf(stderr, "Could not open an image file.\n");
free(buffer);
return 2;
}
do
{
// write the buffer to the new file
fwrite(buffer, 512, 1, image);
// read the next 512B of input
fread(buffer, 512, 1, input);
}// check for the end of jpeg.
while(!((buffer[0] & 0xf0ffd8ff) == 0xe0ffd8ff));
// close the output file
fclose(image);
// change the output file name for the next output
i++;
}
}
// free the heap
free(buffer);
// close the input file
fclose(input);
}