0

The variable count stops incrementing at 1 and I don't know why.

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

typedef uint8_t  BYTE;

int main(int argc, char* argv[])
{
    // check if the number of commandlinearguments is legal
    if (argc != 2)
    {
        fprintf(stderr, "Usage: infile\n");
        return 1;
    }

    // open the input file
    FILE* infileptr = fopen(argv[1], "r");

    // check if file exists
    if (infileptr == NULL)
    {
        fclose(infileptr);
        fprintf(stderr, "Couldn't open file\n");
        return 2;
    }

    // initialize buffer for 512 bytes of the infile
    BYTE buffer[512];

    // initialize counter for filename;
    int count = -0;

    // declare filename
    char filename[7];

    FILE* outfileptr;

    while (fread(buffer, 1, 512, infileptr) == 512)
    {
        // check if new jpeg begins
        if (buffer[0] == 0xff &&
            buffer[1] == 0xd8 &&
            buffer[2] == 0xff &&
            (buffer[3] & 0xf0) == 0xe0)
        {

            // close old file
            if (count > 0)
            {
                fclose(outfileptr);
            }

            // update filename
            sprintf(filename, "%03d.jpg", count);

            // open new file
            outfileptr = fopen(filename, "w");

            // increment file counter
            count++;
        }

        // copy jpeg if there is an open file
        if (count > 0)
        {
            fwrite(buffer, 512, 1, outfileptr);
        }
    }

    return 0;
}
1

When a string (char*) is initialized like this char* filename = "000.jpg"; it is a "string literal", or constant, and is stored in read-only memory. The program will seg fault here sprintf(filename, "%03d.jpg", count); when it tries to change the contents of filename. You'll need to declare filename as a char array, or a char* that is allocated with malloc/calloc (and make sure you allocate enough room for the null terminator in either case!).

Another problem brewing: The comment says // initialize buffer for 512 bytes of the infile. But the allocation int buffer[512]; is 512 ints. Review bmp.h (from resize) for hints on how to make the array a "byte type".

4
  • I've changed the char* to an array and no i have no errors. But I have still no images as output. May 25 '17 at 15:26
  • answer edited with additional info. May 25 '17 at 16:09
  • Thank you I've implemented the byte datatype and know I get 2 images. May 25 '17 at 16:21
  • What's wrong with the filename allocation? May 25 '17 at 16:46
0

The problem is that the strings always have a terminating byte \0 so my string is 0 bytes long but I copy it in a 7 byte buffer. And because my counter variable is next to my buffer on the stack i write the terminating byte in my counter variable and set it every iteration to zero.

You must log in to answer this question.

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