Why would I ever open a file (std::ifstream) without std::ios::binary?

≡放荡痞女 提交于 2019-12-05 03:30:29

What can you do in text mode that you can't do in binary? Read text, for starters. A file opened in text mode automatically translates between the '\n' character internally, and whatever the system uses to delimit lines in files externally. It can also recognize an arbitrary end of file, even when the underlying system requires file sizes to be a multiple of some fixed size.

The choice today is somewhat complicated by the fact that you often have to access the files from incompatible systems. If you have a file system mounted on both Windows and Unix, write it as text under Windows, and read it as text under Unix, then you'll see extra characters. In such cases, it may be preferable to read and write binary, and to do the line end handling yourself, according to whatever conventions you prefer. Similarly, if the "file" is actually a socket, communicating with another machine, you'll want to open it in binary, and handle line endings yourself, according to the requirements of the protocol.

Well stdin is opened by default in text mode, this allows the use of for example CTRL + Z to signal EOF so I don't see why you think there is no "need" to have streams opened in anyting except binary mode.

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