My code compiles and runs and the images load and seem fine BUT it skips the first image and ends at 48. There IS an image named 000.jpg that is output but that image under the name 000.jpg from what I understand is actually the image for 001.jpg and so on... (the images are shifted)
a weird file (sometimes named P@) is output instead
does anyone know what might be the reason?
here is my code:
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <stdint.h>
#define BLOCKSIZE 512
int inError();
int main(int argc, char *argv[])
{
// Check for invalid usage
if (argc < 2)
{
return inError();
}
char* input = argv[1];
if (input == NULL)
{
return inError();
}
char filename[8]; // we know it's 8 from: ###.jpg'\0'
// open, check and read from file
FILE *infile = fopen(argv[1], "r");
if (infile == NULL)
{
printf("The file %s cannot be opened for reading\n", filename);
return 1;
}
// create output files
FILE *outfile = NULL;
typedef uint8_t BYTE;
BYTE buffer[BLOCKSIZE];
int jpgCount = 0;
bool isjpghead = false;
bool foundjpg = false;
outfile = fopen(filename,"w");
while (fread(buffer, sizeof(BYTE), BLOCKSIZE, infile))
{
if (buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && (buffer[3] & 0xf0) == 0xe0) //jpg headers begin with this
{
foundjpg = true;
//if it's the jpg header mark boolean as true
if (isjpghead == false)
{
isjpghead = true;
}
else
{
fclose(outfile);
}
outfile = fopen(filename,"w");
sprintf(filename, "%03i.jpg", jpgCount);
//increment jpgcount
jpgCount ++;
//write to output file
fwrite(buffer, sizeof(buffer), 1, outfile);
}
else
{
if (foundjpg)
{
fwrite(buffer, sizeof(buffer), 1, outfile);
}
}
}
//close open files to avoid memory leaks
fclose(outfile);
fclose(infile);
return 0;
}
//output error
int inError()
{
printf("Usage: ./recover image\n");
return 1;
}