0

Here is my code. Please help.

#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <stdbool.h>

#define BLOCK_SIZE 512
#define FILE_NAME_SIZE 8

typedef uint8_t BYTE;

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

    FILE *infile = fopen(argv[1], "r");
    if(infile == NULL)
    {
        printf("File not found.\n");
        return 2;
    }

    BYTE buffer[BLOCK_SIZE];

    bool found_jpg = false;
    int file_count = 0;

    FILE *outfile;

    while(fread(buffer, BLOCK_SIZE, 1, infile))
    {
        if(buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && (buffer[3] & 0xf0) == 0xe0)
        {
            if(found_jpg == false)
            {
                found_jpg = true;
            }
            else
            {
                fclose(outfile);
            }

            char filename[FILE_NAME_SIZE];
            sprintf(filename, "%03i.jpg", file_count++);
            outfile = fopen(filename, "a");

            if (outfile == NULL)
            {
                return 1;
            }
            fwrite(buffer, BLOCK_SIZE, 1, infile);
        }
        else if (found_jpg == true)
        {
            fwrite(buffer, BLOCK_SIZE, 1, infile);
        }
    }

    fclose(outfile);
    fclose(infile);
}
4
  • @stensal please help me figure out the reason for that 🥺🥺 May 25 '20 at 12:58
  • I will take a look.
    – stensal
    May 25 '20 at 13:02
  • fwrite(buffer, BLOCK_SIZE, 1, infile); is this what you intended? writing to infile, should it be outfile
    – stensal
    May 25 '20 at 13:09
  • @stensal well I copied parameters for function but forgot to change the last one. May 25 '20 at 14:10
0

Changing parameter of fwrite from infile to outfile helped me.

You must log in to answer this question.

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