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

#define BLOCK_SIZE 512
#define FILE_NAME_SIZE 8
typedef uint8_t BYTE;
bool is_start_new_jpeg(BYTE buffer[]);

int main(int argc , char* argv[])
{
    if (argc != 2)
    {
        printf("Usage: ./recover image\n");
        return 1;
    }
    FILE* infile;
    infile = fopen(argv[1], "r");
    if (infile == NULL)
    {
        printf("File Not Found\n");
        return 1;
    }
    BYTE buffer[BLOCK_SIZE];
    int file_index = 0;
    bool have_found_first_jpeg = false;
    FILE* outfile;
    while(fread(buffer, BLOCK_SIZE, 1, infile))
    {
        if (is_start_new_jpeg(buffer))
        {
            if (!have_found_first_jpeg)
                have_found_first_jpeg = true;
            else
            fclose(outfile);

            char filename[FILE_NAME_SIZE];
            scanf(filename, "%03i.jpeg", file_index++);
            outfile = fopen(filename, "w");
            if (outfile == NULL)
            {
                return 1;
            }
            fwrite(buffer, BLOCK_SIZE, 1, outfile);
        }
        else if(have_found_first_jpeg)
        {
            fwrite(buffer, BLOCK_SIZE, 1, outfile);
        }
    }
    fclose(outfile);
    fclose(infile);
}
bool is_start_new_jpeg(BYTE buffer[])
{
    return buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && 
(buffer[3] & 0xf0) == 0xe0;
}
0
0

sprintf is your answer, but

  • A separate function 'bool is_start_new_jpeg(BYTE buffer[])' is not necessary.
  • You need filename[9] for ***.jpeg or just use jpg instead.
  • You don't have an exit condition in the while loop (it works anyway though), I doubt fclose(outfile); fclose(infile); will be reached.
  • You don't need a pile of bool variables - file_index is enough.

You must log in to answer this question.

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