0

This is my code for PSET4. Can anyone explain why it is not working? I have tried debugging forever. But I get various combinations of file limit exceeded and segmentation faults that just don't go away.

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

typedef uint8_t  BYTE;

int main(void)
{
int pcounter = 0;

FILE* raw = fopen("card.raw", "r");
if (raw == NULL)
{
    printf("Could not open card.\n");
    return 2;
}

BYTE *buffer = malloc(512);

while ((fread(buffer, 512, 1, raw)) != 0)
{                
    char str[7];
    if (buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && (buffer[3] & 0xf0) == 1110)
        sprintf(str,"%03d.jpg", pcounter);
        pcounter++;
        FILE* outptr = fopen(str, "w");
        do
        {
            fwrite(buffer, 512, 1, outptr);
            fread(buffer, 512, 1, raw);
        }    
        while (buffer[0] != 0xff && buffer[1] != 0xd8 && buffer[2] != 0xff && (buffer[3] & 0xf0) != 1110);
        fclose(outptr);
}

free(buffer);
fclose(raw);

}

1 Answer 1

0

In the first place:

char str[7];

Is incorrect you must leave enough space for the end-of-string character:

char str[8];

Second:

&& (buffer[3] & 0xf0) == 1110)

& Is a bit-level operator, you should write something like:

(buffer[3] >= 0xe0 && buffer[3] <= 0xef)

thirdly the logic of your program is very wrong, not allow you to properly write to each new found jpg, here tines pseudocode that can help you:

initiate image counter to zero
initiate a flag to zero

while fread read something (a question about how to do this is a good question)
    IF find a new jpg
       IF the jpg file is open 
           we closed it
        //end IF
       sprint title
       open new jpg
       increase counter
       we make flag 1
   // end IF

    IF flag is 1
       we write in jpg
// end while

fclose files
//end main

You must log in to answer this question.

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