Noah Gonzales Noah Gonzales - 6 months ago 95
C Question

CS50: recover.c ~ What data type would hold bytes (512 to be specific) of a JPG?

I am trying to recover files (JPG's) from a damaged memory card my problem set in CS50 at Harvard. I am supposed to make a buffer (512 bytes long), read from the memory card onto the buffer, then see if the buffer starts with the same stuff as a JPG. Here it is:

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

//0xff 0xd8 0xff 0xe0
//0xff 0xd8 0xff 0xe1

#define BLOCK 512
#define START1END 0xe0
#define START2END 0xe1

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

//making variables
int found = 0;
char* title;
FILE* img;
int ifopen = 1;

FILE* buffer[512];

int main(int argc, char* argv[])
//opening file
FILE* inptr = fopen("card.raw", "r");
//checking if file opening failed
if (inptr == NULL)
return 2;
//sets the begins or jpgs
uint8_t checkjpg1[4] = {0xff, 0xd8, 0xff, 0xe0};
uint8_t checkjpg2[4] = {0xff, 0xd8, 0xff, 0xe1};

//making buffer
unsigned char buffer;

//going through the file
while(fread(&buffer,sizeof(char),BLOCK,inptr) == BLOCK)
//checking if begin == the possible begin of jpg
if ((buffer[0] == checkjpg1[0] && buffer[1] == checkjpg1[1] && buffer[2] == checkjpg1[2]) &&
(buffer[3] == checkjpg1[3] || buffer[3] == checkjpg2[3]))
//if a jpg is not open
if (ifopen == 1)
//make one
img = fopen(title,"a");
//end the one and open new one
img = fopen(title,"a");



I think I got it down, or am I way off? It keeps giving this error:

recover.c:70:40: error: incompatible pointer types passing 'unsigned char *' to
parameter of type 'FILE *' (aka 'struct _IO_FILE *')
/usr/include/stdio.h:716:38: note: passing argument to parameter '__s' here
size_t __n, FILE *__restrict __s);

But when I change "unsigned char" to FILE*, it throws the same error but with FILE*. What is it asking for? Thank you in advance, I'm still struggling to get a grip on CS!


You would use

unsigned char buffer[512];

for the variable that holds the data you read.

The 4th parameter of fwrite() is the stream that you want to write to, not the buffer that you want to write. So you might have


instead of having the buffer and img the other way around. However, the buffer you have declared is not suitable.

You have two variables called buffer, one is an array of 512 FILE * pointers, and the other is a single unsigned char. Your code in main() cannot see the former variable, because the variable declared in main() hides it. But that variable is 1 byte long, you are not going to hold 512 bytes of anything in it. You want an array of 512 unsigned chars.