CS50_Labs/Lab4/recover/recover.c

66 lines
1.6 KiB
C

#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
int main(int argc, char *argv[])
{
//check if user used correct arguments
if (argc != 2)
{
printf("Usage: ./recover image\n");
return 1;
}
typedef uint8_t BYTE;
//initialize variables
BYTE buffer[512];
FILE *file_output = NULL;
char filename[8];
int counter = 0;
int img_opened = 0;
//open file and read into file_input
FILE *file_input = fopen(argv[1], "r");
//read data from file input to buffer in blocks of 512 B
while (fread(&buffer, 512, 1, file_input))
{
//check if first bytes match with jpg format
if (buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && (buffer[3] & 0xf0) == 0xe0)
{
//check if image was already found in previous loop
if (img_opened == 1)
{
fclose(file_output);
}
else
{
img_opened = 1;
}
//write in filename name based on counter with at least 3 position + .jpg
sprintf(filename, "%.3i.jpg", counter);
// initialize file output with correct name
file_output = fopen(filename, "w");
counter++;
}
//if image is opened, write 512 B block of data from buffer to file_output
if (img_opened == 1)
{
fwrite(&buffer, 512, 1, file_output);
}
}
//close both input & output files if not used anymore
if (file_input == NULL)
{
fclose(file_input);
}
if (file_output == NULL)
{
fclose(file_output);
}
}