I'm working on the recover problem, but when my code gets to the if statement I made that checks for the header of a JPEG file, it gets stuck.
I get no errors, it simply stops iterating through the loop. I also found that when I printed out the integer values of the first four elements of the array they were all 0.
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <stdbool.h>
typedef uint8_t BYTE;
int main(int argc, char *argv[])
{
// Make sure only one argument is given
if (argc != 2)
{
printf("Usage: ./recover image");
return 1;
}
// Open file with given argument
FILE* file = fopen(argv[1], "r");
// Return from main if there is no file with that name
if (file == NULL)
{
printf("Usage ./recover image");
return 1;
}
// Initialize variables
BYTE arr[512];
bool fileOpen = false;
FILE* ptr;
int n = 0;
char filename[7];
// Loop
printf("loop reached\n");
while(1 == 1)
{
// Read 512 bytes to array 'arr'
printf("iteration\n");
fread(arr, sizeof(BYTE), 512, file);
// If the end of the file has been reached, break the loop
if (feof(file))
{
printf("broken\n");
break;
}
// Check for JPEG header
if (arr[0] == 0xff && arr[1] == 0xd8 && arr[2] == 0xff && (arr[3] & 0xf0) == 0xe0)
{
if (fileOpen)
{
// Close last file
fclose(ptr);
}
// Create filename
if (n < 10)
{
sprintf(filename, "00%i.jpg", n);
}
else if (n < 100)
{
sprintf(filename, "0%i.jpg", n);
}
else
{
sprintf(filename, "%i.jpg", n);
}
ptr = fopen(filename, "a");
// Write to the file
fwrite(arr, sizeof(BYTE), 512, ptr);
// A file is open
n++;
fileOpen = true;
}
else
{
fwrite(arr, sizeof(BYTE), 512, ptr);
}
}
// Close the file
fclose(file);
}