My code compiles and saves 50 JPG images with proper names, but when I try to open any one of them, all of them are blank, just grid. When I run check50
, I get Segmentation fault
error.
What I'm doing wrong?
Here is pseudo-code:
- try to read 512 bytes from memory card
- failure:
- exit
- success:
- check first four bytes
- not JPG's first four
- output file already opened?
- no:
- go to start (read next 512 bytes)
- yes:
- write to that file
- go to start
- JPG's first four:
- output file already opened?
- no:
- open new
- write to file
- go to start
- yes:
- close already opened output file
- open new file
- write to file
- go to start
Here is actual code:
// recovers 'deleted' JPEGs from memory card
#include <stdio.h>
#include <cs50.h>
#include <stdbool.h>
#include <ctype.h>
// generate new file name
char *fileName(int i)
{
char *filename = malloc(8);
sprintf(filename, "%03i.jpg", i);
return filename;
}
// open file
FILE *openFile(char *filename)
{
return fopen(filename, "wb");
}
int main(int argc, char *argv[])
{
// ensure proper usage
if (argc != 2)
{
fprintf(stderr, "Provide a path to forensic image.\n");
return 1;
}
char *infile = argv[1];
// open input file
FILE *inPointer = fopen(infile, "r");
if (inPointer == NULL)
{
fprintf(stderr, "Could not open %s.\n", infile);
return 2;
}
unsigned char buffer[512];
int i = -1;
int numberOfBytes;
FILE *outputFilePointer = NULL;
char *filename = NULL;
while ((numberOfBytes = fread(buffer, 1, 512, inPointer)) > 0)
{
// check first 4 bytes
if (buffer[0] == 0xff &&
buffer[1] == 0xd8 &&
buffer[2] == 0xff &&
(buffer[3] & 0xf0) == 0xe0)
{
// already opened?
outputFilePointer = openFile(filename);
if (outputFilePointer != NULL)
{
// yes:
// close file
fclose(outputFilePointer);
free(filename);
// open new file;
i++;
filename = fileName(i);
outputFilePointer = openFile(filename);
}
else
{
// no:
// open new file
i++;
filename = fileName(i);
outputFilePointer = openFile(filename);
}
// write to outputFile
fwrite(buffer, 1, numberOfBytes, outputFilePointer);
}
else
{
// alredy opened?
outputFilePointer = openFile(filename);
if (outputFilePointer != NULL)
{
// yes:
// write to outputFile
fwrite(buffer, 1, numberOfBytes, outputFilePointer);
}
// no:
// next read
}
}
if (outputFilePointer != NULL)
{
fclose(outputFilePointer);
}
if (inPointer != NULL)
{
fclose(inPointer);
}
free(filename);
return 0;
}