0

So, I'm using quarantine to learn C. I'm currently stuck at the Recover problem. My code compiles, runs but the result is not what I would've expected. I've explained this code to myself a thousand times and it seems perfect, but it doesn't work the way it should. I know that putting the whole code is not good practice, but I don't know what else to do. Here it goes:


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

    if (argc != 2) {
        return 1;
    }

    FILE* file = fopen(argv[1], "r");

    int fcounter = 0;

    int buffer[512];

    char filename[8];

    while (fread(buffer, 1, 512, file) != 0) {

        if (buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && (buffer[3] & 0xf0) == 0xe0) {

            if (fcounter == 0) {

                sprintf(filename, "%03i.jpg", fcounter);

                FILE* img = fopen(filename, "w");

                fwrite(buffer, 1, 512, img);

                fcounter++;

                fclose(img);

            } else {

            sprintf(filename, "%03i.jpg", fcounter);

            FILE* img = fopen(filename, "w");

            fwrite(buffer, 1, 512, img);

            fcounter++;

            fclose(img);

            }

        } else if (fcounter != 0) {

            FILE* img = fopen(filename, "w");

            fwrite(buffer, 1, 512, img);

            fclose(img);

        }

    }
    
}
1

When you read a byte of data from the a file, the data type you store that data in should be 1 byte. In the notes, they use unsigned char because that goes from 0 to 255, which is what you want.

Also, think about the difference between 'w' and 'a' modes for writing to a file. 'w' clears what's already in the file, and writes starting at the beginning. 'a' leaves the already written data in the file, and adds the new data to the end. Which of those do you want to use where in your program? The way you have things set up, you'll use both in different places.

| improve this answer | |
  • That was literally it. Didn't knew about the 'a' mode (don't think they mention it in the lectures?). Thanks a bunch! – Antônio Gabriel Zeni Landim Jul 2 at 20:52

You must log in to answer this question.

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