Skip to content

Instantly share code, notes, and snippets.

@RicLouRiv
Last active August 29, 2015 14:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RicLouRiv/a76aca2ca07cf819b8a1 to your computer and use it in GitHub Desktop.
Save RicLouRiv/a76aca2ca07cf819b8a1 to your computer and use it in GitHub Desktop.
cs50 pset4 recover.c
#include <cs50.h>
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#define CHUNK 512
typedef uint8_t BYTE;
int main(void)
{
// open "card.raw"
FILE* inptr = fopen("card.raw", "r");
if (inptr == NULL)
{
return 1;
}
// set JPG counter
int jpg = 0;
// initialize file pointer
FILE* outptr = NULL;
// process the file
while (!feof(inptr))
{
// create buffer
BYTE buffer[CHUNK];
// read data into buffer
fread(&buffer, sizeof(buffer), 1, inptr);
// are we at the start of a JPG?
if (buffer[0] == 255 && buffer[1] == 216 && buffer[2] == 255 &&
(buffer[3] == 224 || buffer[3] == 225))
{
// close an open outptr if one is open
if (jpg >= 1)
{
fclose(outptr);
}
// what file should we put data into
char FILENAME[8];
sprintf(FILENAME, "%03d.jpg", jpg);
outptr = fopen(FILENAME, "w");
jpg++;
}
if (jpg > 0)
{
fwrite(&buffer, sizeof(buffer), 1, outptr);
}
}
// close the output file
fclose(outptr);
// close the input file
fclose(inptr);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment