user2014904
user2014904

Reputation: 77

Having issues reading a jpeg file in c

I am currently stuck on being able to ready a jpeg file. It looks like I'm close, but for whatever reason, the file is not reading the distinct signature(s) of a jpeg file.And of course, I'm not sure if I'm doing something wrong or clumsy or what. Here is the code I currently have:

int main (void)
{
    typedef unsigned char BYTE ;
    char image_name[8]; 
    int counter=1;
    FILE* fp = fopen("card.raw", "r");
    FILE *outfile=NULL;
    int size=512;
    BYTE buffer[size];
    while (feof(fp) == false) 
    {
        fread(buffer,size,sizeof(unsigned char),fp);
        if (fp== NULL)
        {
            printf("Could not open file \n");
            return 1;
        }
        if(buffer[0]==255 && buffer[1]== && || buffer[2]==255 && (buffer [3]==224 && buffer[3]==225))
        {  
            for(int i=0; i<51; ++i){        
                sprintf(image_name, "%.3d.jpg", counter);        
                outfile= fopen(image_name, "w");
                fwrite(buffer,sizeof(buffer),1,outfile); 
                counter=counter+1;
                if (outfile == NULL)              
                {                   
                    printf("could not create jpeg file\n");                   
                    return 2;              
                }      
            } 
        }
        fclose(fp);
        fclose(&outfile);
        return 0;
    }

Now, currently I'm only part way through this assignment.

Upvotes: 1

Views: 2323

Answers (2)

Some programmer dude
Some programmer dude

Reputation: 409482

You open the file in text mode, but you should open it in binary mode:

fopen("card.raw", "rb");  /* Notice the `b` for binary mode */

The same when you open for writing.


You also only read a single character, but then check multiple:

/* This reads a single byte (`sizeof(unsigned char)` == 1) */
fread(buffer,size,sizeof(unsigned char),fp);

/* Here you check multiple bytes in the buffer,
 * even though you only have read a single byte
 */
if(buffer[0]==255 && buffer[1]== && || buffer[2]==255 && (buffer [3]==224 && buffer[3]==225))

Also note that the expression buffer [3]==224 && buffer[3]==225 can never be true.

Upvotes: 1

Rohan
Rohan

Reputation: 53386

Syntax of the if(buffer[0]==255 && buffer[1]== && || is not correct.

There should be some value after buffer[1]== instead of &&.

Is that typo in post?

Upvotes: 2

Related Questions