0

So I think I've nearly finished but I've come upon a bit of roadblock. That is all my photo are invalid. I looked at all the threads I could and couldn't find out why.

My Code:

#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)
{
    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");
}
uint8_t *buffer_ptr = malloc(FAT_BLOCK_SIZE);
int jpg_bool = 1;
int num_of_jpgs = 0;
char filename[8];
FILE *img = NULL;
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)
{
    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);
    jpg_bool = 0;
    num_of_jpgs++;
}
if(jpg_bool == 0)
{
    // writes 512 bytes until new jpg found
    fwrite(&buffer_ptr,1,512,img);
}

}

1

A quick glance at the code and I found a significant problem, there may be more.

When the code finds a signature, it goes through the process of closing the old file, opening the new file, and writing the block out to the file.

THEN, it checks to see if a file is open and, if so, writes the block out to the open file.

In other words, it's writing the first block of each file twice. This corrupts the file's header data. There's a real easy fix to this, but I'll let you figure it out with a little thought. ;-)

If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance. ;-)

2
  • Thank you, I fixed that issue. – Ryan Dec 20 '18 at 16:59
  • Would you mind looking at it for one more moment. I added and else to the if statement but all of the files are still invalid. I don't understand why. – Ryan Dec 20 '18 at 17:03

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .