#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <cs50.h>
int main(int argc, char *argv[])
{
#define BUFFER_SIZE 512
FILE *img = NULL;
if(argc == 1)
{
printf("Usage: ./recover image");
return 1;
}
else if(argc > 2)
{
return 1;
}
else if(argc == 2)
{
FILE *file = fopen(argv[1], "r");
if (file == NULL)
{
printf("Cannot open card.raw");
return 1;
}
int file_counter = 0;
unsigned char buffer[BUFFER_SIZE];
while (fread(buffer, BUFFER_SIZE, 1, file) == 1)
{
fread(buffer, BUFFER_SIZE, 1, file);
if(buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && (buffer[3] & 0xe0) == 0xe0)
{
file_counter ++;
//Creating the filename
char filename[8];
sprintf(filename, "%03i.jpg", file_counter);
if(file_counter == 1)
{
img = fopen("card.raw", "w");
fwrite(&buffer, BUFFER_SIZE, 1, img);
}
else
{
fclose(img);
img = fopen("card.raw", "w");
fwrite(&buffer, BUFFER_SIZE, 1, img);
}
}
else if(buffer[0] != 0xff || buffer[1] != 0xd8 || buffer[2] != 0xff || (buffer[3] & 0xe0) != 0xe0)
{
if (file_counter > 0)
{
fwrite(&buffer, BUFFER_SIZE, 1, img);
}
}
}
}
//Close any remaining files
fclose(img); //This line of code is causing segmentation fault. But when I remove it, and run the program, nothing happens. All I get is $ on a new line in the command terminal.
return 0;
}
Add a comment
|
1 Answer
The while
executes an fread
followed immediately by an fread
. What is likely happening is: program never finds a jpeg signature because it is only processing every other block. Therefore, no img file is opened, therefore the close gives a seg fault.