0
#include "stdio.h"
#include "cs50.h"
#include "stdint.h"

int main(int argc, char* argv[])
{

// check for command-line arguments
if (argc >= 2)
{
    printf("This program does not accept command-line arguments\n");
    return 1;
}

// array for jpeg names
char jpegName[8];    

// counter
int jpegCounter = 1;

// open file    
FILE* data = fopen("card.raw", "r");
if (data == NULL)
{
    fclose(data);
    printf("Unable to open file.");
    return 1;
}

// create outfile
FILE* jpg = NULL;

uint8_t* buffer = malloc(sizeof(uint8_t) * 512);

while(fread(buffer, 512, 1, data) == 1)
{
    if (buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && (buffer[3] == 0xe0 || buffer[3] == 0xe1))
    {
        if (jpg != NULL)
        {
            fclose(jpg);
        }

        // create file name
        sprintf(jpegName, "%03d.jpg", jpegCounter);

        // create file
        jpg = fopen(jpegName, "a");

        // write the data
        fwrite(buffer, sizeof(buffer), 1, jpg);

        // increment counter
        jpegCounter++;
    }    
}
if (jpg != NULL)
    fclose(jpg);
if (data != NULL)
    fclose(data);
free(buffer);
}

My code SEEMS to work. There's no leaks with valgrind, but I'm having trouble deciphering what gdb is trying to tell me. It creates 16 jpegs, but they're only 4 bytes each which is definitely not right. And, when I try to open them, I get "Error interpreting JPEG image file (Improper call to JPEG library in state 201)". If anyone could give me a hint as to what i'm doing wrong, I'd greatly appreciate it.

6
  • You're only calling fwrite when the signature was found, so your program will, of course, only write to a file on the block the signature was found. – Irene Oct 28 '15 at 3:52
  • Ok, so it's only writing the first 4 bytes that are found and not continuing? Do I need to add another fread and a while loop to check to make sure the next set of 512 isn't a jpg? – Mark Piland Oct 28 '15 at 3:55
  • No. It's writing the 512byte block that contains the signature. You have to account for what happens if the fread block doesn't contain it – Irene Oct 28 '15 at 4:00
  • If it doesn't contain it, would it not just do another loop and read the next 512 bytes? – Mark Piland Oct 28 '15 at 4:05
  • well, you can do it in different ways. I don't really understand why you would have another loop. If it doesn't contain it, you need to write the bytes anyway, in case there's already an existing jpeg – Irene Oct 28 '15 at 4:50

You must log in to answer this question.

Browse other questions tagged .