In 'recover' I wanted to jump out of my while loop if the fwrite() function of the last photo (of the file) returns a value < 512 (indicating that the last photo or end of file is reached). I wanted to assign it to an int variable called 'status'. But somehow in debug50 it seems like the variable doesnt get assigned the return value properly and so my while loop runs indefinitely.
Any thoughts on how I could implement this without writing the whole code all over again?
If there are any other thoughts on my code, hit me. Want to learn as much as I can.
#include <stdio.h>
#include <cs50.h>
#include <stdlib.h>
#include <stdint.h>
int main(int argc, char *argv[])
{
//argv commands: if not one argument after prog: "Usage: ./recover image", return 1
if (argc != 2)
{
printf("Usage: ./recover image\n");
return 1;
}
//open memory card; if opening not possible print and return 1
char *input = argv[1];
FILE *inputptr = fopen(input, "r");
if (input == 0)
{
printf("File could not be opened.\n");
return 1;
}
typedef uint8_t byte;
byte buffer[512];
char *filename = malloc(8);
bool first_found = false;
int counter = 0;
bool eof = false;
int status = 513;
FILE *outputptr = NULL;
//Repeat until end of card
while(status >= 512) //until end of card
{
//read 512bytes into a buffer and watch for jpeg start bytes
fread(buffer, sizeof(byte), 512, inputptr);
//if start of new jpeg
if (buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && ((buffer[3] & 0xf0) == 0xe0))
{
//else: every other after first we have to close previous file
if (first_found == true)
{
counter++;
fclose(outputptr);
sprintf(filename, "%03i.jpg", counter);
outputptr = fopen(filename, "w");
fwrite(buffer, sizeof(byte), 512, outputptr);
}
//if first jpeg
if (first_found == false)
{
first_found = true;
sprintf(filename, "%03i.jpg", counter);
outputptr = fopen(filename, "w");
fwrite(buffer, sizeof(byte), 512, outputptr);
}
}
//else: writing in already open jpeg
else if (first_found == true)
{
status = fwrite(buffer, sizeof(byte), 512, outputptr);
}
}
//close reamining files, free() memory
fclose(inputptr);
fclose(outputptr);
printf("Successful, goodbye.\n");
free(&filename);
return 0;
}