Proper/Efficient way to determine size of stdin in C

后端 未结 5 831
逝去的感伤
逝去的感伤 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:19

    FILE objects in ANSI C represents streams. Personally, I would have named the type STREAM rather than FILE, but that's another issue.

    Anyway, FILE objects represent streams of information. Some stream sources, represents a chunk of data. Such sources are files and memory blocks. Other stream sources, such as pipes and socket connections, do not represent a chunk of data. They represent a (possibly) infinite stream of bytes. There is no definite beginning, because the pipe may have been read from earlier, and later redirected to you. There is also no definite end either, because data may arrive on the stream forever and ever (or at least until someone turns off the power ;).

    stdin represents a pipe type of stream. It has no definite beginning and no definite end. Therefore it cannot be measured reliably.

    If you want to know at any given time how much data has been read from the stream, you'd have to create some abstraction layer ontop of the FILE functions (or somehow hook into it - don't know about such features in ANSI C), and keep your own record. Note however, that you cannot know that the first byte you read from the stream is the first byte ever to have been read from it, because it may have been redirected to you after it has been read from.

提交回复
热议问题