Question

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;
}
Was it helpful?

Solution 2

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.

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top