How does <iostream> work? (C++)

老子叫甜甜 提交于 2020-02-01 07:03:59

问题


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).


回答1:


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.




回答2:


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).




回答3:


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)




回答4:


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.



来源:https://stackoverflow.com/questions/895058/how-does-iostream-work-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!