0

I am very new to programming and am having problems with a segmentation fault in the code below. Any sort of guidance on where I have gone wrong would be very much appreciated.

It is most likely associated with the fwrite function but I am unsure on what part of the function to alter.

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

const int jpeg_size = 512;

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

char * file = argv[1];

FILE *input = fopen(file, "r");
{
    if (input == NULL)
    {
        fprintf(stderr, "Could not open file\n");
        return 2;
    }


    unsigned char buffer[jpeg_size];

    FILE *photo = NULL;
    int f_count = 0;
    char filename[8];

    while (fread(buffer, 1, jpeg_size, input) == 1)
    {
        if (buffer[0] == 0xff &&
        buffer[1] == 0xd8 &&
        buffer[2] == 0xff &&
        (buffer[3] & 0xf0) == 0xe0)
        {
            if (f_count != 0)
            {
                fclose(photo);
            }
            sprintf(filename, "%03i.jpg", f_count);

            photo = fopen(filename, "a");
            if (photo == NULL)
            {
                fprintf(stderr, "Could not create photo %s. \n", filename);
                return 3;
            }
            f_count++;
            fwrite(buffer, 1, jpeg_size, photo);
        }
        else if (f_count > 0)
            {
                fwrite(buffer, 1, jpeg_size, photo);
            }

            if (f_count == 49)
                {
                fclose(input);
                fclose(photo);
            }
            return 0;
        }
    }

}

2
  • Have you run debug50 to find out exactly where it is crashing?
    – curiouskiwi
    Jul 15 '18 at 4:41
  • @curiouskiwi the problem was with the fread.... line. I now can write all the photos to jpeg but i get the "file size limit exceeded" error. Any help for that?
    – benrob1996
    Jul 17 '18 at 11:41
0
while (fread(buffer, 1, jpeg_size, input) == 1) 

change to

while (!feof(input))

check how much you actually read the data from the file input and write the same number in the file photo

 numberReadBytes = fread(buffer, 1, jpeg_size, input);

and write to file photo

fwrite(buffer, 1, numberReadBytes, photo);

You must log in to answer this question.

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