here's the code i wrote:
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
typedef uint8_t BYTE;
//take command line argument from the user for the file name
int main(int argc, char *argv[])
{
if (argc != 2)
{
printf("Invalid Input\n");
return 1;
}
//since jpegs are of 512 bytes, declare an array of BYTES of size 512
BYTE buffer[512];
FILE *img;
int count = 0;
char *fname = malloc(sizeof(char) * 10);
//open the .raw file
FILE *f = fopen(argv[1], "r");
if (f == NULL)
{
printf("File not found!\n");
return 1;
}
//declare a bool value, for checking if the first jpeg is encountered, also declare a integer count as 0, to keep track of the number of jpegs found.
int First_File = 1;
//read 1 byte at a time, store 512 such bytes in the array as jpegs are stored back to back as packets of 512 bytes, read until the loop reaches EOF
while (fread(&buffer, 1, 512, f) != 0)
{
//check if the first 4 elements of the array satisfy a specific condition
if (buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && (buffer[3] & 0xf0) == 0xe0)
{
// if found first jpeg is false
if (First_File == 1)
{
// set the bool as true
First_File = 0;
// declare and open a new file
sprintf(fname, "%03i.jpg", count);
img = fopen(fname, "w");
// write into it 512 bytes one byte at a time
fwrite(buffer, 1, 512, img);
// increment the count
count++;
}
else
// else
{
fclose(img);
// close the previous file
// declare and open a new file
sprintf(fname, "%03i.jpg", count);
img = fopen(fname, "w");
// write into it 512 bytes one by one
fwrite(buffer, 512, 1, img);
// increment the count
count++;
}
}
// else continue reading
}
fclose(img);
fclose(f);
// close the last file
free(fname);
}
When i run the code using ./recover card.raw, it returns segmentation fault I think i am not reading the file correctly when the if condition is not satisfied, but i'm stuck! can someone please point me to the right direction?