My recover.c programme returns unknown type on the cs50 ide, but on a different IDE, it compiles but stops short at the if statement that checks if it is a valid jpg file. Then returns segmentation fault.
#include <stdio.h>
#include <stdlib.h>
// Programme recovers deleted jpgs from a file/memory card
int main(int argc, char *argv[])
{
typedef uint8_t BYTE;
BYTE *buf = (BYTE*)malloc(512 * sizeof(BYTE));
int i = 0;
int num = 1;
FILE *fp;
char *filename = (char*)malloc(20 * sizeof(char));
// check if user complies
if(argc != 2)
{
fprintf(stderr, "Usage: %s FILENAME\n", argv[0]);
return 1;
}
// Check if file opens successfully
if((fp = fopen(argv[1], "r")) == NULL)
{
fprintf(stderr,"Couldn't open %s\n", argv[1]);
return 1;
}
FILE *img;
// Loop through Memory card
while((fread(buf, 512, num, fp)) == 1)
{
// Check if it is a valid jpg
if(buf[0] == 0xff && buf[1] == 0xd8 && buf[2] == 0xff && (buf[3] & 0xf0) == 0xe0)
{
// Check if it is the first jpg found
if(i == 0)
{
sprintf(filename, "%03i.jpg", i);
img = fopen(filename, "w");
}
else
{
i++;
fclose(img);
sprintf(filename, "%03i.jpg", i);
img = fopen(filename, "w");
}
fwrite(buf, 512, num, img);
}
else
{
fwrite(buf, 512, num, img);
}
}
free(filename);
free(buf);
fclose(img);
fclose(fp);
return 0;
}