The code compiled but has segmentation fault. I've checked it with Valgrind, the fault seems relevant to the file pointer. Does file pointer work the same way as other types of pointer? If not, what's the difference?
I have another question about the fread() function as well. By putting the fread() into the while-condition part, do I need to repeat fread() in the while-do part? Will the code keep reading till the end of the file if I don't? I'm confused because in other posts I've seen people using fread() only once in the while-condition part, but I find it not so reasonable if it works this way.
I've been doing this pset for three weeks no less than 4 hours per day, watched the videos again and again, and have done tons of research, yet still not have not fully grasped the main points. The learning curve in this pset is far too steep. Many concepts or jargons like stderr, stream are not even mentioned in the videos or spec, yet they cram the documentation.
I am so desperate and lost. Someone please help me out. Thank you!
#include <stdio.h>
#include <stdlib.h>
#define BLOCK 512
int main(void)
{
// Open car.raw in read mode
FILE* card = fopen("card.raw", "r");
if (card == NULL)
{
printf("Could not open card.raw.\n");
return 1;
}
// Read the card 512 bytes at a time
unsigned char buffer[BLOCK];
fread(buffer, BLOCK, 1, card);// "&" needed or not? NOT!
// If a JPEG signature "0xff 0xd8 0xff 0xe(0-f)" is found,
// close the old image and create a new image and write data to it.
// When the end of car.raw is reached, close all files and end the program.
char title[8];
int img_num = 0;
FILE* img = NULL;
while (fread(buffer, BLOCK, 1, card) == 1)// Check the end of the card.
{
if (buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && buffer[3] >= 0xe0 && buffer[3] <= 0xef)
{
if (img_num == 0)
{
sprintf(title, "%03d.jpg", img_num);// E?
img = fopen(title, "w");
}
else
{
fclose(img);
sprintf(title, "%03d.jpg", img_num);// E?
img = fopen(title, "w");
}
img_num++;
}
fwrite(buffer, BLOCK, 1, img);
fread(buffer, BLOCK, 1, card);
}
fclose(card);
fclose(img);
return 0;
}