I got this code to work, but I have a few questions for my own clarification.
On line 68 where I define the jpg title, why is it a single character? The actual title 001.jpg is much longer than a character. Any why does 'char pic[8];' have to show an array of 8?
In fwrite(), the code works correctly either with bookmark or &bookmark as the first parameter. Why is this? Is it because it only has to be set as the address one time, and was already set in fread()?
In sprintf(pic, "%03d.jpg", counter); are we using a 3 because the number format shows 3 digits? This ran correctly with either d or i. Is that important, whether it runs as an integer or double? Is there any difference here?
Thanks for any clarification.
/**************************************************************************** * recover.c * * Computer Science 50 * Problem Set 4 * * Recovers JPEGs from a forensic image. ***************************************************************************/
#include <stdio.h>
#include <stdint.h>
int main(int argc, char *argv[])
{
// define and store the string for the cmd line argument to take card.raw
char *cardraw = (argv[1]);
// ensure proper usage
if (argc != 2)
{
fprintf(stderr, "Usage: ./recover card.raw\n");
return 1;
}
FILE *card = fopen(cardraw, "r");
if(card == NULL)
{
printf("Error opening the file \"ecard.raw\"...");
return 2;
}
//Alternate way
//check that the file to open is not null
// if ((f = fopen(card, "r")) == NULL)
// {
// printf("Error opening the file \"ecard.raw\"...");
// return 1;
// }
//create an address (or pointer) for reading
//uint8_t is a byte, an unsigned integer 8 bits long
//the array contains 512 bytes
//byteDatatype arrayName[# in array] - to create an array of bytes
uint8_t bookmark[512];
//create a variable for the size
int block = 512;
//initialize the while loop
int counter = 0;
//set the outfile construct pointer to null
FILE *pix = NULL;
// Iterate over file contents to read
while(fread(&bookmark, block, 1, card))
{
//JPEG header starts with same 3 bytes - 0xff 0xd8 0xff 0xe Last byte start with 1110 or 0xe 1-9 or 0xe a-f
// Check if the first four bytes are a JPEG signature
if(bookmark[0] == 0xff && bookmark[1] == 0xd8 && bookmark[2] == 0xff &&(bookmark[3] & 0xf0) == 0xe0)
{
// Close the file, if it is opened
if(pix != NULL)
{
fclose(pix);
}
// create an array for each individual jpg title
//?why is this only a character? why is it an array of 8?
char pic[8];
//store the jpg title in sprintf
// sprintf(outfile, "%03d.jpg", variable for the jpeg #);
//? the 3 means 3 digits?
sprintf(pic, "%03d.jpg", counter);
// Open the new JPEG file for writing and store in the outfile
pix = fopen(pic, "w");
counter++;
}
//if outfilefile is open, then continue writing to it
if(pix != NULL)
{
//? why does this also work as bookmark with no ampersand?
fwrite(&bookmark, block, 1, pix);
}
}
//after reading
//if outfile is open, then close it
if(pix != NULL)
{
fclose(pix);
}
//close infile
fclose(card);
//success
return 0;
}