What does 'stream' mean in C?

后端 未结 6 1991
无人及你
无人及你 2021-02-15 23:40

I\'m reading a section in \'C Primer Plus\' which deals with files, streams and keyboard input. The author connects the concept of stream with files and defines stream as follow

6条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-02-16 00:24

    I struggled with the same question when first came across it. :) But please note that files and streams are quite different things. Files are just sequences of bytes. Now on the other hand, any program (most of them) will normally need to interact with their environment(could be files, could be devices, could be network, etc.) so the stream comes in here nicely.

    A stream is an interface(an easy "face" to work with something with many subtleties irrelevant to us, just like a TV remote!) for triggering input/output flow of data, to or from anything that can be a destination or source to that input/output data, hiding the implementation details of the numerous possibilities of OS methodologies and hardware designs from programmers(you as a programmer are not really interested into knowing about how various operating systems deal with files on low level, or how they interact with a network socket, or with a monitor, and so on, right?).

    So for instance, if you want to read/write to file, you first need a stream. You create a stream for that file (in C) using the fopen() function from the standard input/output library. The thing that is returned is of course a pointer to something called FILE but that’s a traditional “bad choice of word” for stream(https://www.gnu.org/software/libc/manual/html_node/Streams.html), so yes, FILE type in C is indeed the data structure representing a stream!(I see..., crazy!)

    Also, as another example, the way your program can get input from keyboard, how does that happen? That happens through a hidden(automatically made) stream the OS makes for ANY program as soon as they get run and again, standard input/output library of C, gives you access to that through a pointer called “stdout”(stdout is a pointer to the output stream, a stream automatically made by the OS for your program when you run it).

    Also as an example in C++ world, you know that in there things are in classes and objects instead of structures, so there you will encounter (as an example) an object called "cout" which is indeed an output stream "object". It will be triggered to show something on the monitor(by default) if you use its "<<" method(AKA an overloaded operator). You see, you didn't need to write any more code for sending something from your program to the monitor! You know cout is already prepared and connected to that! That's awesome, isn't it?

    Here is also a pretty decent explanation if you need to read further: http://www.qnx.com/developers/docs/6.5.0/topic/com.qnx.doc.dinkum_en_c99/lib_file.html

    HTH.

提交回复
热议问题