0
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
    if(argc != 2)
    {
        fprintf(stderr, "Usage: ./recover <filename>\n");
        return 1;
    }

    char *jpg = argv[1];

    FILE *inptr = fopen(jpg, "r");

    if (inptr == NULL)
    {
        fprintf(stderr, "Couldn't open the file\n");
        return 2;
    }

    unsigned char buffer[512];
    int jcount = 0;
    char fname[7];
    int stat = 0;
    FILE *img;

    while (fread(&buffer, 512, 1, inptr))
    {

        if (buffer[0] == 0x0ff && buffer[1] == 0xd8 && buffer[2] == 0xff && (buffer[3] & 0xf0) == 0xe0)
        {


            if (stat == 1)
            {
                fclose(inptr);
                sprintf(fname, "%03i.jpg", jcount);
                img = fopen(fname, "a");
                jcount++;
            }

            if(!stat)
            {
                sprintf(fname, "%03i.jpg", jcount);
                img = fopen(fname, "w");
                stat = 1;
                jcount++;
            }
            fwrite(&buffer, 512, 1, img);
        }



        else
        {
            if (stat == 1)
            {
                fwrite(&buffer, 512, 1, img);
            }

        }
    }
    fclose(inptr);
    fclose(img);
    return 0;

}

Whats wrong with my code? Spent hours looking for a bug.

  • I got it i was closing inptr when i was supposed to close img – Varun Beluguli Sep 16 '19 at 18:50
  • 1
    Glad to hear it! Always happy to see anyone solve their own problems!!!! Now, can you please write it up as an answer and then accept it (when the system allows)? Otherwise, it'll remain in the unanswered question pool forever. thanks. – Cliff B Sep 16 '19 at 19:20
0

I was closing inptr when i was supposed to close img. So subtle! Didn't even notice it for 1 hr

You must log in to answer this question.

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