1

I'm working with USB and I want to read the content of usb device descriptor in /dev/bus/usb/00x/00y - it is a character device.

I used fopen to open it as a binary file with "rb" parameter. But when I do the seek and tell to get file size, it returned 0 bytes in size. Is there a way to read it as a binary file?

void ReadUsbDeviceDescriptor( const char* path )
{
    FILE* usb_fd = NULL;
    size_t lSize = 0;

    if ( path != NULL )
    {
        usb_fd = fopen ( path, "rb");
        if ( usb_fd != NULL )
        {
            fseek( usb_fd , 0 , SEEK_END );
            lSize = ftell (usb_fd);
            rewind( usb_fd );

            printf("File: %s - Size: %lu bytes\n", path, lSize);

            fclose( usb_fd );
        }
        else
        {
            printf("Could not open file %s\n", path );
        }
    }
}

And here is the result:

File: /dev/bus/usb/001/001 - Size: 0 bytes
2
  • 1
    As it's not a regular file, the fseek is likely failing, if you check the resultcode ? Commented May 21, 2021 at 10:33
  • @steve You're right, fseek failed. As @RalfFriedl said below, I can use fread to read byte one by one to the end of the file, then get the length. Thank you for your help. Commented May 24, 2021 at 2:57

1 Answer 1

3

As steve mentioned, file size is rarely meaningful on a character device.

So the solution is simply open, read, be done. What is even the purpose of ftell here? If you want to allocate a buffer in advance, the answer is, you can't.

I suggest you try what your program does with /dev/tty. Maybe first think what you expect would or should happen.

Another point is that on Unix systems, all files are binary, so mode rb is not necessary. On systems like Windows it makes a difference, but it's unlikely that there even exists a /dev/usb on Windows.

1
  • Thank you for your suggestion. I can use fread to read byte one by one to get the length. It worked well. Thanks again! Commented May 24, 2021 at 2:59

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.