I am doing the task for cs50, I need to restore all the jpg images from the memory card, which are copied from the card to the card.raw file. Below is the working code. But if I declare a variable count below the array, i.e. like this
BYTE jpgBlock[512]; int count = 0; The program stops working correctly. Namely, in the while loop after the first pass of the inner loop (when the jpg signature is found and the 1st image is recorded to the end - that is, until the signature of the next picture is found) at the end, the counter increases and the count is 1, going to 2 pass after line
sprintf(outfile, "%03d.jpg", count); the counter is reset, i.e. count becomes 0. Why so? Why it depends on whether count is declared higher or lower than BYTE jpgBlock [512];
#include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <cs50.h> typedef uint8_t BYTE; int main(void) { FILE *inptr = fopen("card.raw", "r"); if (inptr == NULL) { return 1; } int count = 0; BYTE jpgBlock[512]; while(1) { char outfile[7]; sprintf(outfile, "%03d.jpg", count); FILE *outptr = fopen(outfile, "w"); if(outptr == NULL) { return 2; } for (int countFirstBlock = 0; fread(jpgBlock, sizeof(jpgBlock), 1, inptr) == 1; ) { if(jpgBlock[0] == 255 && jpgBlock[1] == 216 && jpgBlock[2] == 255) { ++countFirstBlock; } if(countFirstBlock == 1) { fwrite(jpgBlock, sizeof(jpgBlock), 1, outptr); } if(countFirstBlock == 2) { break; } } fclose(outptr); if(feof(inptr)) { break; } fseek(inptr, -(int)sizeof(jpgBlock), SEEK_CUR); ++count; } fclose(inptr); return 0; }