CS50 Recover Solution

By Suraj Chaudhary

Are you looking for the solution of Harvard’s CS50 PSet 4? Do you want the CS50 Recover Solution of week 2?

If so you’re in the right place.

In this article, I’m going to share with you exactly how to solve the CS50 Recover problem and will also share the CS50 Recover solution with you.

Here’s how to solve the CS50 Recover problem.

The first thing to do is to understand what we are trying to build. You can read the instructions from CS50’s website.

Here’s my entire code for the CS50 Recover Solution in the file recover.c:

#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>

#define BLOCK_SIZE 512
typedef uint8_t BYTE;

void ArgumentCount(int argc);
void doesFileExists(FILE *file);
int JPEG_check(BYTE tempb[]);

int main(int argc, char *argv[])
{
    ArgumentCount(argc);
    FILE *raw = fopen(argv[1], "r");
    doesFileExists(raw);

    BYTE tempb[BLOCK_SIZE];

    char fName[8];
    FILE *img;
    int counter = 0;

    while (fread(tempb, BLOCK_SIZE, 1, raw) == 1)
    {
        if (JPEG_check(tempb) == 1)
        {
            if (counter != 0)
            {
                fclose(img);
            }
            sprintf(fName, "%03i.jpg", counter++);
            img = fopen(fName, "w");
            fwrite(tempb, BLOCK_SIZE, 1, img);
        }
        else if (counter > 0)
        {
            fwrite(tempb, BLOCK_SIZE, 1, img);
        }
    }
    fclose(raw);
    fclose(img);
}

void ArgumentCount(int argc)
{
    if (argc != 2)
    {
        printf("Usage: /recover image\n");
        exit(1);
    }
}

void doesFileExists(FILE *file)
{
    if (file == NULL)
    {
        printf("File could not be opened. \n");
        exit(1);
    }
}

int JPEG_check(BYTE tempb[])
{
    if (tempb[0] == 0xff && tempb[1] == 0xd8 && tempb[2] == 0xff && (tempb[3] & 0xf0) == 0xe0)
    {
        return 1;
    }

    return 0;
}

If you have any confusion or problem, feel free to drop a comment down below. In the meantime, you can read these articles.

Also Read

  1. CS50: How To Study At Harvard For FREE (and get a free certificate)
  2. How to use Windows 11 on Mac for Free
  3. How To Get A Domain Name For FREE
  4. How To Use Microsoft Office Apps For FREE Legally (Mac & PC)

Suraj Chaudhary is a writer, developer, founder, and a constant learner. He shares lessons and resource to living a fuller life every week. On this blog, he shares helpful guides and helpful articles that help his 70,000+ monthly readers find answers, solve problems, and meet their curious needs.

Leave a Comment

Slide to prove you're not a bot/spammer *