0

This is my code for pset4 recover. Only one file is being opened, with no picture, and then I get a segmentation fault error. Any ideas why?

 /**
 * recover.c
 *
 * Computer Science 50
 * Problem Set 4
 *
 * Recovers JPEGs from a forensic image.
 */

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

int main(int argc, char* argv[])
{
typedef int bool;
#define true 1
#define false 0
char* card = "card.raw";
unsigned char buffer[512];
int byte = sizeof(char);
char title[4];
bool FIF = false; // FIF = First Image Found

FILE* outptr = NULL;
// opens card.raw for reading with pointer named file
FILE* inptr = fopen(card, "r");
if (inptr == NULL)
{
    printf("Could not open.\n");
    fclose(inptr);
    return 1;
}

int a = 0;
int b = 0;
int c = 0;


// repeat as long as it reads 512 bytes successfully
while(feof(inptr) == 0)
{

    fread(&buffer, byte, 512, inptr);

            // if start of JPG is found
            if (buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff
            && (buffer[3] == 0xe0 || buffer[3] == 0xe1))
            {


                // printf("%d\n", FIF);
                if (FIF == true)
                {
                    fclose (outptr);
                }

                if (FIF == true)
                {
                    a++;

                    if (a > 9)
                    {
                        b++;
                        a = 0;
                    }
                }

                sprintf(title, "%d%d%d.jpg", c, b, a);

                FIF = true;

                outptr = fopen(title, "a");

                if (outptr == NULL)
                {
                    printf("Could not open %s.\n", title);
                    return 2;
                }


            }

            if (FIF == true)
            {
                //printf("about to write to the file\n");
                fwrite(&buffer, byte, 512, outptr);
            }



}
fclose(outptr);
//printf("closed outptr\n");
fclose(inptr);
//printf("closed inptr\n");
return 0;

}

Thank you!

0

When creating the filename, how many characters are in the complete file name? How many characters are allocated to title? And does this account for the end of string marker?

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

3
  • Thank you! For some reason though, the first picture is the only one that is messed up. Do you know why that could be? – Elliot Berdy Jun 21 '16 at 3:41
  • Never mind. Got it! – Elliot Berdy Jun 21 '16 at 3:42
  • Yes, I knew exactly. And now, you should too. ;-) – Cliff B Jun 21 '16 at 3:52

You must log in to answer this question.

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