I'm new to writing programs that read or write files and I am totally stuck as to the reason I keep getting a segmentation fault. I feel like it might have to do with one of my file pointers or newly created files, but any help by more experienced eyes would be greatly appreciated!
Another piece of information - while I was trying to debug the program, it seemed to be stuck checking the if statements around line 35 for longer than I would expect, then eventually - segmentation fault.
Here is my complete code below:
// program to recover deleted JPEGs from memory card
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
// ensure proper usage
if (argc != 2)
{
fprintf(stderr, "Usage: recover inputFile\n");
return 1;
}
// remember filename
char *infile = argv[1];
// open input file
FILE *inptr = fopen(infile, "r");
if (inptr == NULL)
{
fprintf(stderr, "Could not open %s.\n", infile);
return 2;
}
// read raw input file
int buffer[512];
int counter = 0;
char filename[8];
FILE* img;
// repeat until EOF
while (fread (&buffer, 1, 512, inptr) == 512)
{
//fread (&buffer, 1, 512, inptr); // this might be redundant (while statement)
// check for start of JPEG
if (buffer[0] == 0xff &&
buffer[1] == 0xd8 &&
buffer[2] == 0xff &&
(buffer[3] & 0xf0) == 0xe0)
{
if (counter > 0) // if this is not the first jpeg found, we need to close previous jpeg
{
fclose(img);
}
// create and open file
sprintf(filename, "%03i.jpg", counter);
counter ++; //keep track of current jpeg count
img = fopen(filename, "w");
// make sure our pointer wasn't NULL
if (img == NULL)
{
fprintf(stderr, "Could not open %s.\n", filename);
return 2;
}
do
{
// Write current buffer to JPEG
fwrite (&buffer, 512, 1, img);
fread (&buffer, 1, 512, inptr);
}
// making sure to stop at start of new JPEG
while ((buffer[0] == 0xff &&
buffer[1] == 0xd8 &&
buffer[2] == 0xff &&
(buffer[3] & 0xf0) == 0xe0) == 0);
// move cursor back one 512 byte block so it can be re-read for if-statement
fseek (inptr, -512, SEEK_CUR);
}
}
// close remaining open files
fclose(img);
fclose(inptr);
}