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

int main(int argc, char *argv[])
{
// file opened   
    FILE *file = fopen(argv[1], "r");
// user types two inputs
    if (argc != 2)
    {
        return 1;
    }
// ensuring it is a valid file
    if (file == NULL)
    {
    
        return 1;
    }
// initalising the array consists of 4 blocks of 512 bytes so 2048
    unsigned char buffer[512];
    

    FILE *img = NULL;
// keeping a bool
    bool check = false;
// keeping track of jpegs
    int count = 0;


// looping through the card
    while (fread(buffer, 512, 1, file) == 1)
    {
// reading through the bytes
 
// Checking for an jpeg
        if (buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && (buffer[3] & 0xf0) == 0xe0)
        {
            //closing the image
            if (check == true)
            {
                fclose(img);
            }
     
            // condition for jpeg
            else
            { 
                check = true; 
            }
            char name[8];
            // creating a jpeg
            sprintf(name, "%03i.jpg", count);
            // opening a new image
            img = fopen(name, "w");
            fwrite(buffer, 512, 1, img);
            // incrementing the counting
            count++;
            // writing to that file
    
        }
        else 
        {
            fwrite(buffer, 512, 1, img);
        }
    }
//closing all files
    fclose(file);
    fclose(img);

    return 0;
}

1 Answer 1

1

Pasting the whole code without trying to isolate where the Segmentation fault happened is not not cool, @cooldude

Some suggestions on how to debug this nasty error:

  • Add a few printf("going to...\n") before important lines of code (opening file, start loop, etc) to help you pinpoint when and where the problem happened

  • What was he output when compiling? Any messages, errors, warnings? How did you compile it? Please include that!

  • Also include how you executed your program in the command line. Did you use an argument? Was it ./recover card.raw or simply ./recover? Does it make any difference? Any ideas why?

  • Segmentation fault usually happens when you access invalid memory, most likely an invalid index to an array (for example, array[5] when it only had 3 elements.). Re-check your indexes to make sure they are not out of bounds!

2
  • it got compiled sorry for the bad code format. when I ran ./recover card.raw seg fault
    – Cooldude
    Nov 25, 2020 at 6:46
  • Thanks a lot for responding. ./recover it compiled also looking through for troubleshooting errors.
    – Cooldude
    Nov 25, 2020 at 6:54

You must log in to answer this question.

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