Pset4 Recover is different since it uses files; fopen, fcloser, fprintf, and fread. It adds a whole new dimension to the coding. Its change from just formatting conceptions to making sure all the files are opened closed and written to properly.
I've learned enough of these concepts to put together the following code that compiles. It passes the first three checks in check50. But when running the program it still gives segmentation fault. I'm at a loss of knowing what part needs attention. I thought it should at least run.
And explanation of it a little more conceptually as well as what the code is missing would be greatly appreciated.
#include <stdio.h>
#include <stdlib.h>
#include <cs50.h>
int main(int argc, char *argv[])
{
if (argc != 2)
{
fprintf(stderr, "Usage: ./recover image\n");
return 1;
}
FILE * fPointer;
fPointer = fopen("card.raw", "r");
if (fPointer == NULL)
{
printf("Error: File does not exist\n");
return 1;
}
// Output file file for picture set to 0
FILE *img = NULL;
unsigned char* buffer = NULL;
char filename[8];
// Counter for image labels set to 0
int counter = 0;
// Checking flag for use of loops
bool check = false;
int i = 0;
// open memory card
// look for beginning of a jpeg (0xff 0xd8 0xff 0xe_)
// if jpeg, open and make new jpeg file
// if not skip forward 512 bytes
// when found write 512 bytes chunks until a new jpeg is found
// stop, make new file, and continue the process
// until you read end of file
while (fread(buffer, 512, 1, fPointer) == 512)
{
//Else close and continue reading
if (buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && (buffer[3] & 0xf0) == 0xe0)
{
// Yes?
if (check == false)
{
fclose(fPointer);
sprintf(filename, "%03i.jpg", i);
img = fopen(filename, "w");
fwrite(&buffer, 512, 1, img);
fclose(img);
counter++;
i++;
check = true;
//fopen(fPointer, "r");
}
// No?
if (check == true)
{
fclose(fPointer);
img = fopen(filename, "a");
fwrite(&buffer, 512, 1, img);
fclose(img);
}
if (check == true && counter > 0)
{
fclose(fPointer);
sprintf(filename, "%03i.jpg", i);
img = fopen(filename, "w");
fwrite(&buffer, 512, 1, img);
fclose(img);
counter++;
i++;
}
}
}
fclose(fPointer);
fclose(img);
//Success
return 0;
}