0

I have problems with this - first, even though the string is correctly formatted it doesn't keep the leading zeros when it names the file (i checked with gdb and printf). Secondly, for some reason, I manage to get 16 images, but I cannot open them, it says that they start with false beginning (0x32 0x35). any ideas? 3rd -the code itself doesn't stop

Here is the code segment (buffer is an array of 512 BYTEs):

char *cur_name = malloc(8*sizeof(char));
sprintf(cur_name, "%03d.jpg", cur_number);
cur_name[7] = '\0';
printf("%s\n", cur_name);

while ((fread(&buffer, sizeof(BYTE), 512, input)) != EOF)
{
    // skip everything until you reach the signature
    if (started == 0 && !(buffer[0] == 0xff && buffer[1] == 0xd8 && 
    buffer[2] == 0xff && (buffer[3] == 0xe0 || buffer[3] == 0xe1)))
        continue;

    if (started == 0 && buffer[0] == 0xff && buffer[1] == 0xd8 
    && buffer[2] == 0xff && (buffer[3] == 0xe0 || buffer[3] == 0xe1))
    {
        started = 1;  
        sprintf(cur_name, "%3d.jpg", cur_number);
        cur_name[7] = '\0';
        output = fopen(cur_name,"w");
    }
    else if (started == 1 && buffer[0] == 0xff && buffer[1] == 0xd8 
    && buffer[2] == 0xff && (buffer[3] == 0xe0 || buffer[3] == 0xe1))
    {
        fclose(output);
        cur_number++;
        sprintf(cur_name, "%3d.jpg", cur_number);
        cur_name[7] = '\0';
        output = fopen(cur_name,"w");
    }

    // print the input   
    for (int i = 0; i < 512; i++)
    {
       fprintf(output, "%d", buffer[i]);
    }
}
fclose(output);
fclose(input);
0

1) About the string and the leading zeroes, not sure. But you're complicating things way too much. First, you don't need a char* and definitely you don't need malloc (and you use malloc and never free the memory). Second, sprintf will create null terminated strings. No need to add it yourself

2) I can't possibly understand why you're using fprintf to write your file (if that's what you're actually doing). You need to write bytes, not characters.

Also, even if it was possible, you are passing int as a format ("%d") and writing a BYTE (providing that you defined BYTE as an unsigned integer type of 1 byte in size). That is never a good idea.

Use the correct function to write your file

1
  • Hey Irene! Thanks for the help, it was the fprintf all along, and ofc the mistake with the EOF loop (wanted to be the wise guy with the looping). I am still having troubles with the names, but it should soon be sorted! – Milos Mitic Sep 21 '15 at 11:50

You must log in to answer this question.

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