I keep getting "error interpreting jpeg image file (Not a jpeg file: starts with 0x00 0xd8)", even though gdb tells me buffer is 0xff. A similar question has been posted on reddit, but I couldn't make anything with the answers there. Does anyone know the problem in this case?
Two main issues in your code
you're not checking whether the EOF was reached which might lead to problems.
the logic of the condition that checks whether a start of a JPG is not met is wrong.
First, as you read from
file, you should check somewhere whether the EOF was reached maybe using a function like
in the terminal for more information about this function. Of course you shouldn't read from the file if the EOF was already reached.
Second, you're writing to the output file as long as a start of a JPG is not met. You're using the following condition to apply this logic
buffer != 0xff && buffer != 0xd8 && buffer != 0xff && (buffer != 0xe0 || buffer != 0xe1)
Although the syntax of this condition is correct, the logic is not and the reason is that
!(x && y)
is not the same as
!x && !y
!x || !y
Long story short, if I say "it will rain today AND it will rain tomorrow.", I'll be proven wrong if it does not rain today OR it does not rain tomorrow. So the negation of
(x && y) is equal to
!(x && y) which is equal to
!x || !y.
Similarly, if I say "it will rain today OR it will rain tomorrow.", I'll be proven wrong if it doesn't rain today AND it doesn't rain tomorrow. So the negation of
(x || y) is equal to
!(x || y) which is equal to
!x && !y.
So the correct condition is
buffer != 0xff || buffer != 0xd8 || buffer != 0xff || (buffer != 0xe0 && buffer != 0xe1)
One last thing is that you should check whether
fopen() has returned
NULL because this too might lead to serious problems if you're trying to read from/write to
Hope that helps!