Created
February 21, 2019 12:57
-
-
Save andrewwylde/428738e8e16f0a70b45925926d7c5983 to your computer and use it in GitHub Desktop.
Attempt at cs50 recover solution
This file contains hidden or 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 <cs50.h> | |
#include <stdint.h> | |
#include <string.h> | |
int logerror(char *msg, int errNum) | |
{ | |
fprintf(stderr, "%s\n", msg); | |
return errNum; | |
} | |
bool check_jpg(unsigned char block[512]); | |
int main(int argc, char *argv[]) | |
{ | |
if (argc != 2) | |
{ | |
return logerror("Usage: ./recover card.raw", 1); | |
} | |
// get the filename and open | |
char *filename = argv[1]; | |
FILE *fileptr = fopen(filename, "r"); | |
if (fileptr == NULL) | |
{ | |
return logerror("Usage: ./recover card.raw", 2); | |
} | |
// file counter needs to start at 0 (000) because it will be used to generate file name | |
int fileCount = 0; | |
bool end = feof(fileptr); | |
bool already_found = false; | |
FILE *outfile = NULL; | |
// initialize a block of length 512 bytes. | |
unsigned char block[512]; | |
// maximum it'll be 6 characters (1000.jpg) | |
char outfilename[8]; | |
while (!end) | |
{ | |
int bytes_read = fread(&block, 1, 512, fileptr); | |
// if the header matches our jpeg header, then start parsing a jpeg | |
bool byte3ok = (block[3] & 0xf0) == 0xe0; | |
bool block0ok = block[0] == 0xff; | |
bool block1ok = block[1] == 0xd8; | |
bool block2ok = block[2] == 0xff; | |
if (byte3ok && block0ok && block1ok && block2ok) | |
{ | |
if (already_found) | |
{ | |
// close previous file | |
fclose(outfile); | |
fileCount++; | |
} else | |
{ | |
already_found = true; | |
} | |
// new filename | |
sprintf(outfilename, "%03d.jpg", fileCount); | |
// new outfile | |
outfile = fopen(outfilename, "w"); | |
fwrite(&block, 1, bytes_read, outfile); | |
} else | |
{ | |
if (already_found) | |
{ | |
fwrite(&block, 1, bytes_read, outfile); | |
} | |
} | |
end = feof(fileptr); | |
} | |
fclose(fileptr); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment