Why would I ever open a file (std::ifstream

2019-04-24 09:26发布

问题:

This may properly belong to a different part of Stack Exchange but I don't think so - programmers.se is more about other things.

Getting to the question: There are things you can do with std::ios::binary that you cannot do in text mode (E.g. relative seek) but I cannot find anything to do in text mode that you cannot do in binary mode - even reading the file as text with e.g. std::getline()

So why would I ever open as text? As a perhaps-related question, why not open as binary by default? Whose use-case does that break?

EDIT Additional information

Here's what's causing me to ask:

I have a file which is created on a windows system - that is, the line-endings are CR LF.

I am opening it with std::ifstream using the std::ios::binary flag

I am parsing through the file with std::getline and getting exactly the behavior I would expect - getline reads one line at a time.

System: Windows 7 Pro

Compiler: g++ for MINGW32

回答1:

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.



回答2:

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.



标签: c++ fstream