I am working on CS50 Recovery and I am unable to get the program to check the JPEG starting header.
I used debug50 and added a couple print statements to try and find the problem. Every time I run the program, it prints out "No Output File 2" meaning no outfile is created, and the IsJPEG boolean check is skipped.
Upon further debugging it seems that the buffer is 0'\000\ all along, so I suspect nothing is written into the buffer, causing the program to skip the boolean check (which trigger fopen) and hence causing it to break.
However, I struggle to find the reason why nothing is written into buffer.
Please help and thank you!
#include <stdio.h>
#include <stdlib.h>
#include <cs50.h>
#include <stdint.h>
typedef uint8_t BYTE;
bool isJPEG(BYTE buffer[]);
int main(int argc, char *argv[])
{
BYTE buffer[512];
int fileCounter = 0;
char filename[8];
if (argc != 2)
{
printf("%s\n", "Usage: ./recovery file");
return 1;
}
FILE* infile = fopen(argv[1], "r");
if (infile == NULL)
{
printf("%s\n", "Error: File Not Found");
return 1;
}
FILE* outfile;
while (fread(buffer, 512, 1, infile))
{
if (isJPEG(buffer))
{
if (fileCounter == 0)
{
sprintf(filename, "%03i.jpg", fileCounter++);
outfile = fopen(filename, "w");
printf("%s\n", "Bool 1");
}
else
{
fclose(outfile);
sprintf(filename, "%03i.jpg", fileCounter++);
outfile = fopen(filename, "w");
printf("%s\n", "Bool 2");
}
if (outfile == NULL)
{
printf("%s\n", "No Output File 1");
return 1;
}
fwrite(buffer, 512, 1, outfile);
}
else
{
if (outfile == NULL)
{
printf("%s\n", "No Output File 2");
return 1;
}
fwrite(buffer, 512, 1, outfile);
}
}
fclose(outfile);
fclose(infile);
}
bool isJPEG(BYTE buffer[])
{
return buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && (buffer[3] & 0xf0) == 0xe0;
}
Now I have moved this code block downwards and it works, but I have no idea why
BYTE buffer[512];
int fileCounter = 0;
char filename[8];
This is the revised code:
#include <stdio.h>
#include <stdlib.h>
#include <cs50.h>
#include <stdint.h>
typedef uint8_t BYTE;
bool isJPEG(BYTE buffer[]);
int main(int argc, char *argv[])
{
if (argc != 2)
{
printf("%s\n", "Usage: ./recovery file");
return 1;
}
FILE* infile = fopen(argv[1], "r");
if (infile == NULL)
{
printf("%s\n", "Error: File Not Found");
return 1;
}
BYTE buffer[512];
int fileCounter = 0;
char filename[8];
FILE* outfile;