This is a common mistake. Look at the first few lines of your loop:
while (!(fread(block, sizeof(block), 1, cardptr) == 0))
fread(block, sizeof(block), 1, cardptr);
You are executing two reads in a row. The result is that you are skipping a block and processing the one following.
The concept that you probably haven't grasped (it was hard for me when I started out) is that when you call a function inside some kind of test code (the control statement of a while or for loop, or an IF statement), you are actually executing the function. The return value from the function is then used in the test. Specifically here, you are executing a read and checking to make sure it was successful, in order to control the while loop. Many new programmers believe incorrectly that you have to execute it inside the loop and you copy the code into the control code for the loop to see if it worked, and also assume that it only checks that it worked the last time it was run. They don't realize it's a full, independent execution of the function call.
This gets even more complicated because you've introduced a third fread(). This third one is actually why you are skipping every other file. It will read a block in, write it to the end of the currently open file, and then it will test for the signature to end the inner loop. Once it finds the jpg signature, it ends the inner while loop and goes back up to the first fread() in the while loop control statement and reads the next two blocks. Since you've gone past the signature block, it will skip forward to the next signature it finds and then open a new file and go through all this again.
This program can be written with a single fread(), and is commonly done with two. The trend has been that the more freads() included in the code, the more problems and the more complex the code becomes.
You would do well to go back and redesign the program as pseudocode. Write out in english what steps should be taken and only once you've worked through it on paper, start converting pseudocode to actual code. Ask yourself these questions:
- Once a block is read, what should be done with it?
- Is there an open output file? IF so, what do I do? If not, should I open a file?
- Should I write the block out or discard it?
- When should I close an output file?
Here's another hint: Sometimes, when writing a program, what appears to be one of the last steps may be one of the first steps. This may sound cryptic, but once you have the program running, (depending on how you design it) it should make sense.
That should get you going again. No guarantees there aren't other issues, but good luck.
If this answers your question, please click the check mark to accept this and remove the question from the unanswered pool. Let's keep up on forum maintenance. ;-)