0

in this pset I should recover 50 every photo is 512 bytes, I should read the data from a file(argv[1]) then if I found a photo header I should write it to a file but it always gives me uncompleted photos any help would be appreciated

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


int main(int argc, char *argv[])
{
    typedef uint8_t BYTE;
    if(argc != 2)
    {
        printf("Usage: ./recover IMAGE\n");
        return 1;
    }
    if (argv[1] == NULL)
    {
        printf("Usage: ./recover IMAGE\n");
        return 1;
    }

    FILE* out = NULL;
    int img_counter=  0;
    FILE* memorycard = fopen(argv[1], "r");
    if(memorycard == NULL)
    {
        printf("Could not open %s.", argv[1]);
        return 1;
    }
    BYTE img[512];
    char* filename = malloc(9 * sizeof(char));

    while (fread (img, 512, 1, memorycard) == 1)
    {
            if(img[0] == 0xFF && img[1] == 0xD8 && img[2] == 0xFF && (img[3] & 0xF0) == 0xE0)
            {
                sprintf(filename,"%03i.jpg",img_counter++);
                out = fopen(filename,"a");
                fwrite(img,512,1,out);
                fclose(out);
            }
    }
    fclose(memorycard);
    return 0;
    }
ali nasser
  • 23
  • 2
  • 2
    For one thing at least, you probably need to [open your files in binary mode](https://stackoverflow.com/q/17598572/10077). – Fred Larson Sep 09 '22 at 14:05
  • 2
    only very small images will fit in 512 bytes – stark Sep 09 '22 at 14:06
  • `if (argv[1] == NULL)` That should never be true if you passed the check above. – Gerhardh Sep 09 '22 at 14:47
  • Your variable naming already reflects your misconception. `BYTE img[512];` This is able to hold **one block** of an image, not a complete image. You will have to write multiple blocks into the same output file. – Gerhardh Sep 09 '22 at 14:50
  • StackOverflow can only work properly if you provide feedback on suggestions or questions in comments or answers. – Gerhardh Sep 10 '22 at 13:46

0 Answers0