0

(int j is just for checking)

typedef uint8_t BYTE;
typedef struct
{
    BYTE buff[512];
}__attribute__((__packed__))
BUFFER;


int main(int argc, char* argv[])
{    
// open input file 
FILE* infile = fopen("card.raw", "r");
if (infile == NULL)
{
    printf("Could not open\n");
    return 1;
}

int j = 0;
int count = -1;
BUFFER buffer;
while(!feof(infile))
{   
    fread(&buffer, sizeof(BUFFER), 1, infile);
    READ:
    if (buffer.buff[0] == 0xff && buffer.buff[1] == 0xd8 && buffer.buff[2] == 0xff && (buffer.buff[3] == 0xe0 || buffer.buff[3] == 0xe1))
    {        
        char title[] = "000.jpg";
        sprintf(title, "00%d.jpg", count + 1);
        FILE* img = fopen(title, "a");

        if (count != -1)
        {
            fclose(img);
        }
        count += 1;
        printf("Found (start of) %d pictures!\n", count);
        printf("Found one\n");
        sleep(3);

        fwrite(&buffer, sizeof(BUFFER), 1, img);
        fread(&buffer, sizeof(BUFFER), 1, infile);

        while (buffer.buff[0] == 0xff && buffer.buff[1] != 0xd8 && buffer.buff[2] != 0xff && (buffer.buff[3] != 0xe0 || buffer.buff[3] != 0xe1))
        {
            fwrite(&buffer, sizeof(BUFFER), 1, img);
            fread(&buffer, sizeof(BUFFER), 1, infile);
        }

        goto READ;
    }

    j++;
    printf("%d\n",j);
}
}
1
  • glad you got your question answered but it's kinda unclear what you're exactly asking. please edit your question and add more details as oppose to dumping code. see cs50.stackexchange.com/help/how-to-ask!
    – kzidane
    Jul 7 '15 at 20:56
2

Your code creates the files but never writes anything into them. If you run ls -al you will see that all the file sizes are 0. This happens because you search for a block with a signature, then read another block then test for the signature again (it won't be there in the next block), and only if this second test passes, you write to the file. The net result is that you never write a 512 byte block to a jpg file.

Looking at the code, it's too complex - too many tests, too many reads, a goto, global variables and structures, etc. It will also fail check50 on filenames when you get to 10. You need to simplify it dramatically. You should think in straightforward logic:

// read a block
// test for signature
// if signature, close any open file, if any, and open a new one.
// if a file is open, write the block.
// repeat until eof
// close last file.
//end

It's that simple. This should get you started.

If this answers your question, please accept this answer to remove the question from the unanswered question pool. Let's keep up on forum housekeeping. ;-)

You must log in to answer this question.

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