Everytime I try to run this code, it gives me a segmentation fault error. What is wrong with my logic?
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
// Ensures proper usage
if (argc != 2)
{
fprintf(stderr, "Usage: ./recover card.raw\n");
return 1;
}
// Remembers arguments
char *raw_image = argv[1];
// Opens image
FILE *raw_file = fopen(raw_image, "r");
if (raw_file == NULL)
{
fclose(raw_file);
fprintf(stderr, "Could not open %s.\n", raw_image);
return 2;
}
// Counts JPEGs
int jpegCounter = 0;
unsigned char buffer[512];
// Stores JPEG names
char jpegs [10];
// Creates output file for JPEGs
FILE *img = NULL;
while (1)
{
// Reads card.raw
fread(&buffer, 512, 1, raw_file);
// Checks if JPEG
if (buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff &&
(buffer[3] & 0xf0) == 0xe0)
{
// Names JPEGs by number
sprintf(jpegs, "%03i.jpg", 2);
// Opens found jpeg
img = fopen(jpegs, "w");
fwrite(&buffer, 512, 1, img);
// Adds to counter
jpegCounter++;
}
else
{
fwrite(&buffer, 512, 1, img);
}
// on end of file terminate program
if (feof(raw_file))
{
fclose(raw_file);
fclose(img);
return 0;
}
}
// close file
fclose(raw_file);
// Success!
return 0;
}