I am currently working on pset4 recover.c. My code complies correctly, but when I run it, only two files are outputted (000.jpg & 001.jpg), which I believe there should be 50 files. I'm not sure why this happens. The images that print out are crystal clear--there is nothing wrong with the first two images. Would anyone have any insight on this? Here is my code below:
Side note: I've seen examples where the condition in the 'while' loop is 'while(fread(buffer, 1, 512, card_ptr) == 1)', where mine is set at 'while(true)'. I've tried changing the while condition to this and didn't see any change.
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <stdbool.h>
typedef uint8_t BYTE;
int main(int argc, char *argv[])
{
//check for eligible command-line arguments
if (argc != 2)
{
printf("Usage: ./recover image\n");
return 1;
}
//declare file pointer and open input file
char *infile = argv[1];
FILE *card_ptr = fopen(infile, "r");
if (card_ptr == NULL)
{
printf("Could not open file\n");
return 1;
}
//declare variables
BYTE buffer[512];
FILE *outfileptr = NULL;
char filename[8];
int jpeg_found = 0;
//read old file and write new file
while (true)
{
outfileptr = fread(buffer, 1, 512, card_ptr);
bool jpgheader = (buffer [0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && (buffer[3] & 0xf0) == 0xe0);
int counter = 0;
//if the start of a jpeg (not the first jpeg), close previous one
if (jpgheader && outfileptr != NULL)
{
fclose(outfileptr);
counter ++;
}
//if the start of a jpeg, then open file and write to that file
if (jpgheader)
{
sprintf(filename, "%03i.jpg", counter);
outfileptr = fopen(filename, "w");
}
if (outfileptr != NULL)
{//write to
fwrite(buffer, 1, 512, outfileptr);
}
}
fclose(outfileptr);
fclose(card_ptr);
}