0

Everything works except the first jpeg gets the name 1 instead of 001

#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>  //includes BYTE struct
#include <cs50.h>

typedef uint8_t BYTE;

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

    // Open file
    FILE *inptr = fopen(argv[1], "r");
    if (!inptr)
    {
        printf("Cannot read file\n");
        return 1;
    }

    FILE *outptr = NULL;  //create file for JPEGS
    int jpegCount = 0;
    char jpegTitle[8];
    BYTE buffer[512];  //Creating buffer
    while (fread(&buffer, sizeof(BYTE), 512, inptr) == 512)
    {
        //if a new jpeg is starting
        if (buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && (buffer[3] & 0xf0) == 0xe0)
        {
            //if there was previous jpeg open, close it and write new one
            if (outptr != NULL)
            {
                //close previous jpeg
                fclose(outptr);
                outptr = NULL;

                //write new one
                sprintf(jpegTitle, "%03i.jpg", jpegCount);
                outptr = fopen(jpegTitle, "w");
                if (!outptr)
                {
                    printf("Cannot open %s\n", jpegTitle);
                    return 1;
                }
                fwrite(&buffer, sizeof(buffer), 1, outptr);
                jpegCount++;
            }
            //if first jpeg
            if (outptr == NULL)
            {
                sprintf(jpegTitle, "%3d.jpg", jpegCount);
                outptr = fopen(jpegTitle, "w");
                if (!outptr)
                {
                    printf("Cannot open %s\n", jpegTitle);
                    return 1;
                }
                fwrite(&buffer, sizeof(buffer), 1, outptr);
                jpegCount++;
            }
        } else if (jpegCount > 0)  //if not starting jpeg just write buffers to file
        {
            fwrite(&buffer, sizeof(buffer), 1, outptr);
        }
    }

    // Close files
    fclose(inptr);
    fclose(outptr);

    //success
    return 0;
}
0

Compare your two sprintf.

BTW, you could move the common code out of that if/else (disguised as two if). Less duplicate code.

You must log in to answer this question.

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