-1

Not Sure why my program is not making valid Jpegs! I am almost done!! Anyways, here is my code. I suspect it has something to do with the first write from buffer (the ones that detect jpeg file).

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

int main(void) <br/>
{ <br/>
    //lets open up card.raw <br/>
    FILE* inptr = fopen("card.raw", "r");

    //we need to make sure we can open card.raw
    if(inptr == NULL)
    {
    fclose(inptr);
    printf("Could not open card.raw\n");
    return 1;
    }

    //we need to create our buffer to store 512 bytes
    //we also want to keep track of our files
    uint8_t buffer[512];
    char titlez[8];

    FILE* outptr = NULL;
    //lets create counters to store image and check for first
    int imgnumz=0;
    int alreadyFound=0;

    //we want to repeat the following lines of code until the end of the card is reached.
    while(! feof(inptr))
    {
        //we want to read 512 bytes at a time into our buffer
        fread(&buffer, 512*sizeof(uint8_t), 1, inptr);

        while(alreadyFound == 0 && !(buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && (buffer[3] == 0xe0 || buffer[3] == 0xe1)))
        {
           fread(buffer, 512*sizeof(uint8_t), 1, inptr); 
        }

        //lets check to see if we are at the beginning of a jpg
        if(buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && (buffer[3] == 0xe0 || buffer[3] == 0xe1))
        {

            //lets store our jpeg files
            sprintf(titlez, "%03d.jpg", imgnumz);

            //we want to create an output file to write to
            outptr = fopen(titlez, "a");
            if (outptr == NULL)
            {
                fclose(inptr);
                printf("Could not write to outptr\n");
                return 1;
            }

            //lets write from our buffer into our output file 512 bytes at a time
            fwrite(&buffer, 512*sizeof(uint8_t), 1, outptr);

            //we need to update our counters
            alreadyFound++;
            imgnumz++;     
        }

        else if (alreadyFound !=0)
        {
            outptr = fopen(titlez, "a");

            //lets again check if we can open outfile
            if(outptr == NULL)
            {
                fclose(inptr);
                printf("Could not write to outptr\n");
                return 1;
            }

            //we need to write the from our buffer into our outfile
            fwrite(&buffer, 512*sizeof(uint8_t), 1, outptr);
            fclose(outptr);

        }

    }

    //lets make sure our files are closed.

    fclose(inptr);
    return 0;   
}
0

I figured it out, soooo pumped! I rewrote a lot of code basically got rid of the redundant fread. Then on my if loop that checks for beginning of jpeg I had to check if outptr was open and close it if so.

You must log in to answer this question.

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