0

I have been trying to think of a way to also use for loop in addition to the do while loop version. I feel logically it could work, however there might be a lot of implementations that are bad and I can't get it to work. It compiles and runs but no files are created. Can anyone point out some major flaws for me please?

Thank you so much!

char* infile = argv[1];
char filename[6];

// open input file 
FILE* raw = fopen(infile, "r");
if (raw == NULL)
{
    printf("Could not open %s.\n", infile);
    return 2;
}

FILE*outfile = NULL;

// Create a buffer
unsigned char Buffer[512];

for (int i = 0; i < sizeof(raw)/512; i++)
{
    int counter = 0;
    fread(&Buffer, 512, 1, raw);
    if (Buffer[i] == 0xff && Buffer[i+1] == 0xd8 && Buffer[i+2] == 0xff && (Buffer[i+3] == 0xe0 || Buffer[i+3] == 0xe1))
    {           
        counter++;
        sprintf (filename, "%d.jpg", counter-1);
        if (filename[i] != filename[i-1])
        {
            outfile = fopen(filename, "w");
        }
    }
    if (counter > 0 && i%512=0)
    {
        fwrite(&Buffer, 512, 1, outfile);
    }

}

2 Answers 2

1

Well, the first problem is that your FOR loop will not execute at all. sizeof(raw) will return the size of the pointer variable raw as an int, not the file size. Since it's only 4 bytes, 4/512 in int arithmetic = 0. You'll need to find a function that will actually get the file size. I'm sure there is one. ;-)

Next, to make sure it works correctly, you'll have to deal with file sizes that don't end on a 512 byte boundary, or you'll probably leave that last partial block unprocessed.

You have other issues, such as not closing the previously opened output file, but I'll let you dig into all that on your own. It's your experiment. ;-)

If this answers your question, please click on the check to accept. Let's keep up on forum housekeeping. ;-)

1
  • Thanks Cliff. It does seem that there are a lot of issues. While I'll try to make it work, I will stick to the while loop for the pset since it's much simpler to implement. Thanks again! Sep 29, 2015 at 2:42
0

Ok, nvm, using for loop will significantly complicate things. I will just stick with a while loop.

You must log in to answer this question.

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