0

my code here compiles but does not create the file. Have tried changing many things... any ideas on what i'm missing? Thanks! Will

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

#define FILE_NAME "card.raw"
#define BUFFER_SIZE 512

int main(int argc, char *argv[])
{
    //ensure proper usage
    if (argc != 2)
    {
        fprintf(stderr, "input: ./recover forensic image");
        return 1;
    }

    // open card.raw or exit program if not correct file
    FILE *inptr = fopen(argv[1], "rb");
    //ensure proper file
    if (inptr == NULL)
    {
        fprintf(stderr, "file read error\n");
        return 2;
    }
    FILE *outptr = NULL;

    unsigned char buffer[BUFFER_SIZE];


    //repeat until end of card
    while (fread(&buffer, sizeof(buffer), 1, inptr))

    {
        //read 512 bytes into buffer
        int jpegCounter = 0;

        if (buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff
            && (buffer[3] >= 0xe0 && buffer[3] <= 0xef))
        {
            //if not the very first jpeg
            if (outptr != NULL)
            {
                fclose(outptr);
                outptr = NULL;

            }
            //if very first JPEG

                char jpegImage[8];
                sprintf(jpegImage, "%03i.jpg", jpegCounter);
                outptr = fopen(jpegImage, "wb");
                if (outptr == NULL)
                {
                    printf("could not open %s.\n", jpegImage);
                    return 1;
                }
                jpegCounter++;
                fwrite(&buffer, sizeof(buffer), 1, outptr);
        }

        else if (outptr != NULL)
            {
                fwrite(&buffer, sizeof(buffer), 1, outptr);
            }


    }


    //close all files
    if (inptr != NULL)
    {
        fclose(inptr);
    }

    if (outptr != NULL)
    {
        fclose(outptr);
    }

    //success
    return 0;

}
0

Actually, it does create one file, 000.jpg. The question is why doesn't it create more files? It's actually overwriting the one file over and over.

It seems like its not incrementing the file name. I could tell you why, but that would be too easy. ;-)

Have you run the program through the debugger? Try this. Put a breakpoint at the line jpegCounter++; and then step through the code until you've gone through the while loop until you see the problem. It shouldn't take long. ;-)

If you can't see it, come back and leave a comment.

If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance. ;-)

You must log in to answer this question.

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