Can I get help with this "recover" code? I keep getting a segmentation fault and I can't understand why! It's coming from the second condition (where it's written segmentation fault) in the below code but the logic looks fine to me, that is if there's a file opened already, keep writing what you read!
Thanks guys!
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
int main(int argc, char* argv[]) { typedef uint8_t BYTE; // TODO // open input file
FILE* file = fopen("card.raw", "r");
if (file == NULL)
{
fclose(file);
printf("Could not read the card\n");
return 1;
}
BYTE block [512];
int i = 0;
int m = 0;
int open = 0;
char s[5];
FILE* outptr = NULL;
while (!feof(file))
{
fread(block, sizeof(block), 1, file);
// first condition: the block has an image!
if ((block[0] == 0xff && block[1] == 0xd8 && block[2] == 0xff && (block[3] == 0xe0 || block[3] == 0xe1)))
{
// If file is still open from last loop, close to start a new one!
if (outptr != NULL)
{
fclose(outptr);
printf("file closed at i = %i and m = %i\n", i, m);
open = 0;
}
// Output files names!
sprintf(s, "%0.3i.jpg", i);
// Create outfile
FILE* outptr = fopen(s, "w");
i++;
//marker that outfile is open
open = 1;
if (outptr == NULL)
{
fclose(file);
//marker that outfile is closed
open = 0;
printf("Impossible to create file!! \n");
return 2;
}
fwrite(block, sizeof(block), 1, outptr);
}
else
{
// second condition: no image starts in block AND there IS an out file opened and hasn't been closed!
if (open == 1)
{
// keep writing in file
// Segmentation fault error!!!
fwrite(block, sizeof(BYTE), 512, outptr);
}
// third condition: no image starts in block AND NO out file opened!
// Do nothing, move on to next loop!
}
}
fclose(file);
return 0;