Going crazy here, help much appreciated:). I think I am messing something up with the scope. Here is my analysis for what it's worth: I am declaring img within the if & else conditions. Because of this I can not use it in the final if statement where I must write to the img file. To fix this I previously tried to declare img outside of the do while loop. However that also did not work, because it gave the error message "shadowing local variables". Really don't know how to solve this..
Thanks! CB
/**
* recover.c
*
* Computer Science 50
* Problem Set 4
*
* Recovers JPEGs from a forensic image.
*/
#include <stdio.h>
#include <stdlib.h>
#include <cs50.h>
#include <stdint.h>
int main(int argc, char* argv[])
{
// open card file
FILE* inptr = fopen("card.raw", "r");
if (inptr == NULL)
{
printf("Could not open file\n");
return 1;
}
// initialize jpeg counter at 000
int jpg_no = 0;
// initialize buffer
uint8_t buffer[512];
// repeat until end of file
do
{
// read 512 byes into buffer
fread(&buffer, 512, 1, inptr);
// is it a new jpeg?
if(buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff
&& (buffer[3] == 0xe0 || buffer[3] == 0xe1))
{
// if 1st file, then open 1st file
if(jpg_no == 0)
{
char* title;
sprintf(title, "%03d.jpg", jpg_no);
FILE* img = fopen(title, "a");
}
// else close previous file and open new one
else
{
fclose(img);
char* title;
sprintf(title, "%03d.jpg", jpg_no);
FILE* img = fopen(title, "a");
}
// update the jpeg counter
jpg_no++;
}
// already found a jpeg?
if(jpg_no > 0)
{
// write to open jpeg
fwrite(&buffer, 512, 1, img);
}
}
// while sizeof buffer = 512
while(fread(&buffer, 512, 1, inptr) == 1);
// close remaining files
fclose(img);
fclose(inptr);
// the end
return 0;
}