I've hit a wall and would appreciate some of you more experienced people to help me through or point me in the right direction. Below is my code, and it generates 27 JPEGs all distorted (numberer 0 - 26). Obviously I'm not finding all headers, and I'm reading and/or writing the files wrong somehow. Am I way off??? All constructive help is appreciated :)
/**
* Recover. This program recovers JPEGs you may have believed were lost
forever.
* Usage: ./recover filename
* */
#include <stdio.h>
int main(int argc, char *argv[])
{
// Ensure proper usage, otherwise quit.
if (argc != 2)
{
fprintf(stderr, "Usage: ./recover filename\n");
return 1;
}
// Save the argument to work with later in the program
char *rawData = argv[1];
// Open the file to read, and check that we actually found the file.
FILE* infile = fopen(rawData, "r");
if (infile == NULL)
{
fprintf(stderr, "File not found.\n");
return 2;
}
// Create a bufferArray to be able to look for the JPEG header
unsigned char buffer[512];
// Create a counter to enable filenames to increment.
int counter = 0;
FILE *writingFile = NULL;
// Read through file until EOF is found by indicating less than 512 number of elements successfully read.
while (fread(buffer, 1, 512, infile) == 512)
{
// Read the file into a buffer[]
fread(buffer, 1, 512, infile);
// Determine if the block contains the header of a JPEG.
if (buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && (buffer[3] & 0xf0) == 0xe0)
{
//If already writing to a file, close that file.
if (writingFile != NULL)
fclose(writingFile);
// Name a file to write to, called ###.jpg
char fileName[10];
sprintf(fileName, "%03d.jpg", counter);
// Open a file to write to.
writingFile = fopen(fileName, "w");
// Add one to counter to make the next fileName in sequence.
counter++;
}
// If a file is writing, continue to do so.
if (writingFile != NULL)
fwrite(buffer, sizeof(buffer), 1, writingFile);
}
// Close the last file after the last JPEG.
if (writingFile != NULL)
fclose(writingFile);
// Close the file we read from
fclose(infile);
return 0;
}