#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#define FAT_BLOCK_SIZE 512
// I figured out how to get block size from here "https://cs50.stackexchange.com/questions/28357/pset-4-recover-help-with-reading-512-byte-blocks"
int main(int argc,char *argv[])
// buffer_ptr[0] == 0xff && buffer_ptr[1] == 0xd8 && buffer_ptr[2] == 0xff && (buffer_ptr[3] & 0xf0)==0xe0) while(fread(&buffer_ptr,512,1,infile)
{
// ensures correct number of arguments
if(argc != 2)
{
return 1;
fprintf(stderr,"This function only accepts one file argument, the memory card");
}
// open memory card file
FILE *infile = fopen(argv[1],"r");
if(infile == NULL)
{
return 2;
fprintf(stderr,"Failed to open file");
}
//creates buffer
uint8_t *buffer_ptr = malloc(FAT_BLOCK_SIZE);
//initializes variables
int jpg_bool = 1;
int num_of_jpgs = 0;
char filename[8];
FILE *img = NULL;
// while file can be read
while(fread(buffer_ptr,1,512,infile) == 512)
{
if(buffer_ptr[0] == 0xff && buffer_ptr[1] == 0xd8 && buffer_ptr[2] == 0xff && (buffer_ptr[3] & 0xf0)==0xe0)
{
// Closes file before opening a new one
if(img != NULL)
{
fclose(img);
}
// open a new jpg
sprintf(filename,"%03i.jpg",num_of_jpgs);
img = fopen(filename,"w");
// write block
fwrite(&buffer_ptr,1,512,img);
// This tells the program that there is a found file and it is time to start writing
jpg_bool = 0;
// Increments name
num_of_jpgs++;
}
else if(jpg_bool == 0)
{
// writes 512 bytes until new jpg found
fwrite(&buffer_ptr,1,512,img);
}
}
}
I don't know why the images are wrong. I tried mapping out my algorithm but I couldn't find any faults. Algorithm
Check that are 2 Arguments
Open Memory Card
Create Buffer
Initialize Variables
While file can be read
if signature is at start of block
check for old file and close it
open new file
write block
make it clear that a file has been found
increment name
else if file already found
write block