Code must read 512 bytes at a time from a file that has raw JPEGs in order to retrieve them. When a JPEG is found, all the following blocks of 512 bytes are stored in a a file until a new JPEG is found, once a new JPEG is found, the file img is closed and then opened as new to store a new image. The code runs fine if I comment or erase the fclose(img); line, othwerwise it shows the error above.
Here's the code
#include <stdio.h>
#include <cs50.h>
#include <stdlib.h>
int main (int argc, char *argv[]){
if(argc != 2){
fprintf(stderr, "Usage: ./recovery image\n");
return 1;
}
FILE *card = fopen(argv[1], "r");
if (card == NULL){
fprintf(stderr, "Cannot open image\n");
return 2;
}
FILE *buffer1 = malloc(sizeof(card));
int n = 0;
int picsNum = 0;
while(fread(buffer1, 512, 1, card)){
n ++;
}
//printf("%i", n);
bool foundJPEG = false;
int j = 0;
bool fstJPEG = false;
FILE *img = NULL;
int counter = 0;
fseek(card, 0, SEEK_SET);
for(int i = 0; i < n; i++){
unsigned char fst;
unsigned char snd;
unsigned char thrd;
unsigned char fth;
unsigned char buffer2[508];
fread(&fst, 1, 1, card);
fread(&snd, 1, 1, card);
fread(&thrd, 1, 1, card);
fread(&fth, 1, 1, card);
fread(buffer2, 508, 1, card);
//printf("%i,%i,%i,%i,", fst, snd, thrd, fth);
if(fst == 0xff && snd == 0xd8 && thrd == 0xff && (fth & 0xf0) == 0xe0){
printf("Found\n");
if(fstJPEG){
fclose(img);
}
printf("%i,%i,%i,%i,", fst, snd, thrd, fth);
foundJPEG = true;
picsNum++;
fstJPEG = true;
char JPEG[8];
sprintf(JPEG, "%03i.jpg", j);
j++;
img = fopen(JPEG, "w");
} else {
foundJPEG = false;
}
if(fstJPEG){
fwrite(&fst, 1, 1, card);
fwrite(&snd, 1, 1, card);
fwrite(&thrd, 1, 1, card);
fwrite(&fth, 1, 1, card);
fwrite(buffer2, 508, 1, card);
counter++;
printf("%i,", counter);
}
}
fclose(card);
printf("%i,\n", picsNum);
}