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
steve
  • 21,582
  • 5
  • 48
  • 75
Manh Huynh
  • 13
  • 2
  • 1
    As it's not a regular file, the `fseek` is likely failing, if you check the resultcode ? – steve May 21 '21 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. – Manh Huynh May 24 '21 at 02:57

1 Answers1

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.

RalfFriedl
  • 8,816
  • 6
  • 23
  • 34
  • Thank you for your suggestion. I can use ```fread``` to read byte one by one to get the length. It worked well. Thanks again! – Manh Huynh May 24 '21 at 02:59