0

I wrote a code for recover.c, and though it compiles, it doesn't function properly. I don't know specifically where the issue is, (it could be the entire concept, really) but I'm sure the fread() and fopen() statements are wrong (I feel like I might have the concepts wrong - after declaring a file pointer, is it enough to rename the filename and reopen the pointer to create a new .jpg?) I'm very new to programming, so I apologize if this looks catastrophic.

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

#include <stdbool.h>

#include <stdint.h>


int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        fprintf(stderr, "Usage: ./recover image\n");
        return 1;
    }


    char *infile = argv[1];

    FILE* inptr = fopen(infile, "r");

    if (inptr == NULL)
    {
        fprintf(stderr, "Could not open file %s\n", infile);
        return 2;
    }

    int buffer[512];

    char* filename = NULL;

    bool newfile = false;

    bool writing = false;

    FILE* img = fopen(filename, "w");

    int i = 0;

    //while not eof
    while((fread(buffer, sizeof(1), 512, inptr)) == 512)
    {
        //If it denotes the start of a JPEG
        if (buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && (buffer[3] & 0xf0) == 0xe0)
        {
            newfile = true;

            //If already in a file
            if (writing == true)
            {
                fclose(img);
            }

            //Whether in file or not in file, if found start of new file

                //Make a new clean copy name
                sprintf(filename, "%03i.jpg", i);

                i++; //for when new files are created, they have different names

                //open copy for writing
                img = fopen(filename, "w");

                //write in copy
                fwrite(buffer, sizeof(1), 512, img);
        }

        //If not the start of a JPEG
        else
        {
            //If a new file was already opened
            if (newfile == true)
            {
                writing = true;

                fwrite(buffer, sizeof(1), 512, img);
            }

            //else just discard the data
        }
    }

    free(buffer);

    free(filename);

    fclose(inptr);

    fclose(img);

    return 0;

}
3

on char *filename= NULL you're setting the value of the pointer to NULL, then a few lines after, you're opening the opening the file with the value of that pointer, which is NULL, it won't open. You need to open the file of each image inside a loop. And checkout sprintf()

  • Thank you so much! I changed it to an array instead, and everything worked out! – Hana Ali Jan 19 '19 at 8:41

You must log in to answer this question.

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