#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <stdint.h>
int main(int argc, char *argv[]) { if (argc != 2) { fprintf(stderr, "Usage: ./recover image\n"); return 1; }
char *infile = argv[1];
#include <stdlib.h>
#include <stdbool.h>
#include <stdint.h>
int main(int argc, char *argv[])
{
if (argc != 2)
{
fprintf(stderr, "Usage: ./recover image\n");
return 1;
}
char *infile = argv[1];
FILE* inptr = fopen(infile, "r");
if (inptr == NULL)
{
fprintf(stderr, "Could not open file %s\n", infile);
return 2;
}
int buffer[512];
char* filename = NULL;
bool newfile = false;
bool writing = false;
FILE* img = fopen(filename, "w");
int i = 0;
//while not eof
while((fread(buffer, sizeof(1), 512, inptr)) == 512)
{
//If it denotes the start of a JPEG
if (buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && (buffer[3] & 0xf0) == 0xe0)
{
newfile = true;
//If already in a file
if (writing == true)
{
fclose(img);
}
//Whether in file or not in file, if found start of new file
//Make a new clean copy name
sprintf(filename, "%03i.jpg", i);
i++; //for when new files are created, they have different names
//open copy for writing
img = fopen(filename, "w");
//write in copy
fwrite(buffer, sizeof(1), 512, img);
}
//If not the start of a JPEG
else
{
//If a new file was already opened
if (newfile == true)
{
writing = true;
fwrite(buffer, sizeof(1), 512, img);
}
//else just discard the data
}
}
free(buffer);
free(filename);
fclose(inptr);
fclose(img);
return 0;
}
}