Below are my code for pset4 - Recover, it passed the check50, but I am trying to understand the logic on a particular process of fwrite or file-pointer.
In short, my question is how does line 74
know which file to write on?
My confusion start from the 2nd JPEG file 001.jpg
has been created on line 62
, from my understanding, the JPEG counter JC
should be accumulated to 2
by line line 66
afterwards, and when the 2nd block of data of 001.jpg
is copied from card.raw
to buffer
, since it is not a start for a JPEG, it will jump to the process of line 68
, and then the img
of line 74
should be getting information from line 40
>> line 39
>> line 36
, which is 2
...so it should write to a file it haven't created yet 002.jpg
...How does it know to write on 001.jpg
instead?
Thanks in advance!
as copy and paste doesn't copy line number, so I added a screen-cape here.
But here is my code anyway:
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
typedef uint8_t BYTE;
// Number of bytes in buffer
const int BUFFER_SIZE = 512;
int main(int argc, char *argv[])
{
// TODO:
// Check command-line arguments
if (argc != 2)
{
printf("Usage: ./recover image\n");
return 1;
}
// Open memory card
FILE *raw = fopen(argv[1], "r");
if (raw == NULL)
{
printf("Could not open file.\n");
return 1;
}
// Setup Buffer
BYTE buffer[BUFFER_SIZE];
// Setup JPEG counter
int jc = 0;
// Setup and open jpg file
char filename[16];
sprintf(filename, "%03i.jpg", jc);
FILE *img = fopen(filename,"w");
// Repeat until end of card:
// Read 512 bytes into a buffer
while (fread(buffer, BUFFER_SIZE, 1, raw))
{
// Check the buffer If start of new JPEG
if (buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && (buffer[3] & 0xf0) == 0xe0)
{
// If first JPEG
if (jc == 0)
{
// Start writing JPEG file
fwrite(buffer, BUFFER_SIZE, 1, img);
}
else
{
// Close the current writing file
fclose(img);
// Setup and open new jpg file
sprintf(filename, "%03i.jpg", jc);
FILE *img2 = fopen(filename, "w");
// Write to new jpg file
fwrite(buffer, BUFFER_SIZE, 1, img2);
}
jc++;
}
else
{
// If already found JPEG
if ( jc >= 1)
{
// Keep writing
fwrite(buffer, BUFFER_SIZE, 1, img);
}
}
}
// Close any remaining files
fclose(raw);
}