How does work? (C++)

2020-07-23 05:31发布

Just out of curiosity, how does iostream access the input-output system. (I have a bad habit of constantly reinventing the wheel, and I'm wondering if I can build a custom input-output system to the likes of iostream).

4条回答
家丑人穷心不美
2楼-- · 2020-07-23 05:52

All streams go to a streambuf. That streambuf will depend on the type of stream. An ofstream goes to a fstreambuf; cout goes to some unspecified streambuf. If you want to customize things, cout allows you to get this streambuf and possibly replace it.

A common pattern is the "filtering streambuf", which is a streambuf interface that transforms its input before sending it to another streambuf. This can be combined with cout: take out the original streambuf, wrap that in a filtering streambuf, and put that wrapper back in cout. You don't need to know how the original streambuf works.

查看更多
不美不萌又怎样
3楼-- · 2020-07-23 06:01

For a detailed guide to IOstreams, see the book Standard C++ IOStreams and Locales. After reading it I suspect you will be content to manage with with the status quo - IOStreams are probably the most complex part of the C++ standard library.

查看更多
Root(大扎)
4楼-- · 2020-07-23 06:14

You certainly could reinvent the wheel.

There are a lot of complications added to the stream operators to handle international character sets. After having looked at it reasonably deeply I really didn't care for it much. It's very complicated and completely destroys any chance of easily using inheritance. It works and is available though. (I wanted to change the behavior of the storage it uses during conversions)

查看更多
Evening l夕情丶
5楼-- · 2020-07-23 06:15

It depends...

It somehow interacts with the native IO system of the operating system. It might internally use the C library, which uses system calls to the kernel, or it might use system calls directly. The exact implementation is highly dependent on the platform.

Many people will say don't reinvent the wheel, but it could be a good learning experience. If you are using Windows, look into the Win32 API calls for file handling. If you use Linux, either use the POSIX/C library, or use the system calls (much harder, I would suggest going with the C library).

查看更多
登录 后发表回答