I am working on a photo extraction program for a course I am taking.
For this program, argv[1] is the name of the file from which I want to extract images from. jpg_name relates to the name of each image I am extracting; I am attempting to name each jpg. numerically starting from 1. As there are 50 photos to be extracted, I would like to stop the program after all 50 images have been extracted. Unfortunately, my program is not sure when to terminate, and as such I believe the last photo is being overwritten multiple times, and I am unsure how to fix this. However, photos 1-49 turn out fine, it is just photo 50 I am having issue with.
Things I have tried to far include implementing an if
condition involving fread
where if the program is unable to read 512 bytes of code into the array, it would terminate. Unfortunately, this does not seem to work either. Any suggestions would be appreciated:
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
int main(int argc, char *argv[])
{
if (argc != 2)
{
printf("Invalid entry.\n");
return 0;
}
int counter = 1;
FILE* images;
char jpg_name[8];
// Check if bytes are jpg. signatures.
for (int n = 0; counter < 51; n = n + 512)
{
// Open file for reading.
FILE *file = fopen(argv[1], "r");
if (!file)
{
return 1;
}
unsigned char array[512];
fseek(file, n, SEEK_SET);
fread(array, 1, 512, file); // if EOF, won't have 512 to write into!!!
if (fread(array, 1, 512, file) != 512)
{
return 2;
}
if (array[0] == 0xff && array[1] == 0xd8 && array[2] == 0xff && (array[3] & 0xf0) == 0xe0)
{
// Convert integer to string and store into jpg character array. Increment image number.
sprintf(jpg_name, "%03i.jpg", counter);
counter++;
// Open images file to write into, allocate memory to jpg file to write into, write 512 bytes from array into image file.
images = fopen(jpg_name, "a");
fwrite(array, 1, 512, images);
fclose(images);
}
else // If 1st 4 bytes aren't jpg signature.
{
if (counter > 1)
{
images = fopen(jpg_name, "a");
fwrite(array, 1, 512, images);
fclose(images);
}
}
fclose(file);
}
}