Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * recover.c
- *
- * Computer Science 50
- * Problem Set 4
- *
- * Recovers JPEGs from a forensic image.
- */
- #include <cs50.h>
- #include <stdio.h>
- #include <string.h>
- int main(int argc, char* argv[])
- {
- // TODO
- // Open file
- FILE* inptr = fopen("card.raw", "r");
- // Check if the file exists and can be opened
- if (inptr == NULL)
- {
- printf("Could not open 'card.raw'.\n");
- return 1;
- }
- // Declare the buffer where the block of 512 bytes will be stored
- unsigned char buffer[512];
- // Declare and intialize counter for file
- int fcount = 0;
- // Initialize a variable for file name
- char fname[8];
- // Declare file name temporary variable
- FILE* temp = NULL;
- while (fread(&buffer, sizeof(buffer), 1, inptr)!= 0) // fread to check end of file
- {
- fread(&buffer, sizeof(buffer), 1, inptr);
- while (fread(&buffer, sizeof(buffer), 1, inptr)) // read 512 bytes into buffer
- {
- if ( buffer[0] == 0xff &&
- buffer[1] == 0xd8 &&
- buffer[2] == 0xff &&
- (buffer[3] >= 0xe0 || buffer[3] <= 0xef) ) /*block starts with jpeg header*/ //
- {
- // generate file name
- sprintf( fname, "%03d.jpg",fcount );
- fcount++; // increment file number
- if (temp != NULL)
- {
- fclose(temp); // close file
- }
- // file = Open a new JPEG file
- temp = fopen(fname, "w");
- }
- if (fcount != 0)
- {
- fwrite(buffer, sizeof(buffer), 1, temp); // now write that block to file , I assume it will keep writing till next jpg
- }
- if (temp != NULL)
- {
- fwrite(buffer, sizeof(buffer), 1, temp);
- }
- }
- } // 1st while loop
- if (inptr != 0) /*card file is open*/
- {
- fclose(inptr); // Close it
- }
- }
Add Comment
Please, Sign In to add comment