views:

48

answers:

2

The c++ program below fails to read the file. I know using cstdio is not good practice but that what I am used to and it should work anyway.

$ ls -l l.uyvy

-rw-r--r-- 1 atilla atilla 614400 2010-04-24 18:11 l.uyvy

$ ./a.out l.uyvy

Read 0 bytes out of 614400, possibly wrong file

code:

#include<cstdio>
int main(int argc, char* argv[])
{
    FILE *fp;

    if(argc<2)
    {
            printf("usage: %s <input>\n",argv[0]);
            return 1;
    }

    fp=fopen(argv[1],"rb");
    if(!fp)
    {
            printf("erör, cannot open %s for reading\n",argv[1]);
            return -1;
    }
    int bytes_read=fread(imgdata,1,2*IMAGE_SIZE,fp); //2bytes per pixel
    fclose(fp);
    if(bytes_read < 2*IMAGE_SIZE)
    {
            printf("Read %d bytes out of %d, possibly wrong file\n",
                 bytes_read, 2*IMAGE_SIZE);
            return -1;
    }
    return 0;
}
+2  A: 

You've got the parameters back to front for size and nmemb

http://www.manpagez.com/man/3/fread/

Try instead,

int bytes_read = fread (imgdata, 2*IMAGE_SIZE, 1, fp);

Also, you haven't provided the declaration for the imgdata buffer, you'd want to be sure the buffer is large enough - or has been malloc'd correctly.

Tim Kane
A: 

I resolved the issue by initializing the pointer. Interestingly, reading fails instead of giving a segfault when you try to read into an uninitialized pointer, that was confusing.

Atilla Filiz
It's not so confusing once you know that you have to *provide* a buffer, `fread` doesn't create it for you. Which is actually a good thing, because you really don't want to have a new buffer allocated for every single file operation. Very often, you can re-use the same buffer again and again. (Think performance!) -- As a final hint, in your case, make sure not to initialize `imgdata` as a fixed-size buffer. You should initialize it according to the size of the file you're reading. You can get the file size through calls to `fseek(fp, 0, SEEK_END);` and then `long fileSize = ftell(fp);`
stakx