Honestly, I have been struggling with Week 4, and I have been trying to complete this pset to the best of of my current understanding. I have researched multiple articles on this topic, but I have yet to find one that will help me with where I am stuck at. My code will compile and run, although once it iterates through all 50 files, it just hangs in the terminal and will not finish running until I enter Ctrl + C. I am stuck as to where to look next, as the assignment only says "Odds are, though, the JPEGs that the first draft of your code spits out won’t be correct. (If you open them up and don’t see anything, they’re probably not correct!)". Well, that is what is happening to me, but where do I start to fix my code? Is it all completely wrong and I need to start over? Any suggestions and help is greatly appreciated.
Here is my code:
''''
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
typedef uint8_t BYTE;
int main(int argc, char *argv[])
{
// define command line usage
if (argc != 2)
{
printf("Usage: ./recover image\n");
return 1;
}
// open forensic file
FILE *forensic = fopen(argv[1], "r");
// check if file successfully opened
if (forensic == NULL)
{
printf("Error opening file. Please try again.\n");
return 2;
}
BYTE buffer[512];
int jpegcounter = 0;
char filename[8];
do
{
// check for jpeg header
if (buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && (buffer[3] & 0xe0) == 0xe0)
{
sprintf(filename, "%03i.jpg", jpegcounter);
jpegcounter++;
FILE *img = fopen(filename, "w");
fwrite(buffer, 512, 1, img);
fclose(img);
}
// if not header
else
{
continue;
}
}
while (fread(buffer, 512, 1, forensic) <= 1);
}
''''
check50 returns the following:
:) recover.c exists.
:) recover.c compiles.
:) handles lack of forensic image
:( recovers 000.jpg correctly
timed out while waiting for program to exit
:( recovers middle images correctly
timed out while waiting for program to exit
:( recovers 049.jpg correctly
timed out while waiting for program to exit
Here is my code after applying the help in the comments below:
BYTE buffer[512];
int jpegcounter = 0;
char filename[8];
int counter = 0; // 0 = file is closed, 1 = file is open
FILE *img = NULL;
// while reading a block of data:
while (fread(buffer, 512, 1, forensic) == 1)
{
// if signature found
if (buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && (buffer[3] & 0xf0) == 0xe0)
{
// if output file is open
if (counter == 1)
{
// close it
fclose(img);
counter = 0;
}
else
{
counter = 1;
}
sprintf(filename, "%03i.jpg", jpegcounter);
img = fopen(filename, "w");
jpegcounter++;
}
// if output file is open
if (counter == 1)
{
// write block to output file
fwrite(buffer, 512, 1, img);
}
}
fclose(img);
fclose(forensic);