Thats's my current code.
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
typedef uint8_t BYTE;
int const BLOCK_SIZE = 512;
int main(int argc, char *argv[])
{
if (argc != 2)
{
printf("Incorrect usage\n");
return 1;
}
FILE *file = fopen(argv[1], "r");
if (file == NULL)
{
printf("Could not open the file\n");
return 1;
}
BYTE buffer[512];
int indx = 0;
int irratation= 0 ;
char* filename = malloc(10);
while(fread(buffer, 1, BLOCK_SIZE, file) == BLOCK_SIZE)
{
FILE* ptr = NULL;
if (buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && (buffer[3] & 0xf0) == 0xe0)
{
irratation++;
if(irratation >= 2)
{
indx++;
}
if (indx == 0)
{
sprintf(filename, "%03i.jpg", indx);
ptr = fopen(filename, "w");
fwrite(buffer, 1, BLOCK_SIZE, ptr);
}
else
{
fclose(ptr);
sprintf(filename, "%03i.jpg", indx);
ptr = fopen(filename, "w");
fwrite(buffer, 1, BLOCK_SIZE, ptr);
}
}
else
{
fwrite(buffer, 1, BLOCK_SIZE, ptr);
}
}
return 0;
}
I think I understand how it should work and I try to implement pseudocode from walkthrough, but the problem I am facing is that I don't know how to access the file pointer. I mean if I find new file, then I say that ptr = fopen and I write there, but when I found next one, I can't close previous one, and also the same goes with else statement, when I don't find new file - I can't write to a file that I have already opened as it's in another if statement.
Can you guys give me some advice on that?
First of all, the images are made of more than one block size of 512, what you're doing is writing every 512 bytes into a new file.
And secondly, what does the irratation variable stand for. If you think about it, everytime you find a jpeg prefix that you're checking in the if statement, you can increment the index, and it would be fine, what you're doing is that (after you fix the file problem) irratation is first set to 0, in the while condition, fread reads 512 bytes, irratation is incremented by one and index is not. Index is at zero, it finds the jpeg prefix and writes in a new file. The loop now restarts, and think about what happens, is the irratation truly doing anything?
Another minor thing, your filename is "###.jpg" can you count another time how much space do you need? Don't forget the '\0'!
I tried to just hint as much as I could considering the CS50 Academic Honesty and rules, so try to figure that out!