Proper/Efficient way to determine size of stdin in C

后端 未结 5 835
逝去的感伤
逝去的感伤 2021-01-16 21:49

Based on my previous question, what would be the proper yet efficient way to determine the size of stdin if stdin is coming from a pipe or a

5条回答
  •  一向
    一向 (楼主)
    2021-01-16 22:22

    Under some systems (linux, I know; probably other *nix) you can do:

    #include 
    #include 
    
    ssize_t fd_ready_size(int fd) { 
        int sz;
        int rc;
    
        rc = ioctl(fd, FIONREAD, &sz);
        if (rc) { // rc = -1 or 0
            return rc;
        }
        return sz;
    }
    

    for most any input file. You should NOTICE that I didn't pass in the FILE * here. I did this because it would have been misleading. The stdio FILE can have buffered up data in it that would need to be added to whatever the OS says is ready to be read. This makes things trickier, and I don't know off the top of my head if there is a reasonable way to get that value.

    I returned a ssize_t (which is a signed size type) because that is what is returned by read and write under POSIX systems, and -1 represents the error case.

    If you are using a system that doesn't allow you do that and stat doesn't give you what you want you may have to resort to tricks. One way is to attempt to read a certain size (we will call X) and if you succeed in getting this full amount you can then think "there may be a little bit more" and realloc your buffer to hold some more, and repeat until you get a read that doesn't completely fill the space you have available. If you have any type of polling function available (which you probably do since were calling stat) then you can also use that to try not to call a read function unless you are sure there is data (unless you have the file opened non-blocking in which case it doesn't matter).

提交回复
热议问题