0

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;
}
0

Did you remember to include the needed #include statement????

| improve this answer | |
  • Stdlid.h, yes I did. – Ninety5 Aug 12 at 22:10
  • No, you didn't. #include <stdint.h> – Cliff B Aug 12 at 22:14
  • Thanks a lot. That was actually the problem. – Ninety5 Aug 12 at 22:40

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .