Created
July 2, 2021 16:25
-
-
Save e200/68f92c34b83911758b2b4e3059e6f954 to your computer and use it in GitHub Desktop.
Recover - cs50 (problem set4)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
#include <stdint.h> | |
#include <cs50.h> | |
bool foundNewJpgFile(uint8_t *buffer); | |
int main(int argc, char *argv[]) | |
{ | |
if (argc != 2) | |
{ | |
printf("Invalid filename provided. Please, provide one and only one forensic file name as expected.\n"); | |
return 1; | |
} | |
FILE *sourceFilePtr = fopen(argv[1], "r"); | |
if (!sourceFilePtr) | |
{ | |
printf("Unable to read the given file. Reason: file doesn\'t exists or is unreadable.\n"); | |
fclose(sourceFilePtr); | |
return 1; | |
} | |
int fileNumber = 0; | |
bool isRecoveringJpgFile = false; | |
char *recoveredFilename = malloc(sizeof(char) * 8); | |
FILE *recoveredFile = NULL; | |
uint8_t *buffer = malloc(sizeof(char) * 512); | |
while (fread(buffer, sizeof(uint8_t), 512, sourceFilePtr)) | |
{ | |
if (foundNewJpgFile(buffer)) | |
{ | |
if (isRecoveringJpgFile) | |
{ | |
fclose(recoveredFile); | |
fileNumber++; | |
} | |
sprintf(recoveredFilename, "%03i.jpg", fileNumber); | |
recoveredFile = fopen(recoveredFilename, "w+"); | |
if (!recoveredFile) | |
{ | |
printf("Unable to start the recovery process. Reason: You may be running out of memory.\n"); | |
fclose(recoveredFile); | |
return 1; | |
} | |
if (!isRecoveringJpgFile) | |
{ | |
isRecoveringJpgFile = true; | |
} | |
} | |
if (isRecoveringJpgFile) | |
{ | |
fwrite(buffer, sizeof(char), 512, recoveredFile); | |
} | |
} | |
free(buffer); | |
fclose(recoveredFile); | |
fclose(sourceFilePtr); | |
} | |
bool foundNewJpgFile(uint8_t *buffer) | |
{ | |
return buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && (buffer[3] & 0xf0) == 0xe0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment