本声明here似乎不正确:
Bidirectional file streams, on the other hand, do not have the flag set implicitly. This is because a bidirectional stream does not have to be in both input and output mode in all cases. You might want to open a bidirectional stream for reading only or writing only. Bidirectional file streams therefore have no implicit input or output mode. You must always set a bidirectional file stream's open mode explicitly.
否则,这段代码将无法编译。
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
fstream file("novo.txt", ios::out);
char i;
file >> i;
}
最佳答案
gcc 声明为真
This statement here doesn't seem to be correct: […]
我不知道标准或 Visual Studio,但我知道我正在使用的 C++,它来自 GCC。在那里你可以看看the relevant header .
oistream::open
看起来像这样:
inline void
istream::open(const char* __s, ios_base::openmode __mode = ios_base::in) {
if (!_M_filebuf.open(__s, __mode | ios_base::in))
所以这里有两件事:一个默认函数参数,以防你在调用方法时没有指定参数,还有一个forced标志,它总是或-进入提供的模式。所以无论你指定什么模式,输入模式总是会被添加到你的规范中。其他代码,尤其是构造函数,将委托(delegate)给它。 ofstream::open
也会出现类似的情况。 .另一方面,fstream::open
有默认参数,但没有强制参数:
inline void
fstream::open(const char* __s,
ios_base::openmode __mode = ios_base::in | ios_base::out) {
if (!_M_filebuf.open(__s, __mode))
因此,不通过任何模式是可以的(至少在此实现中,但阅读@kmote 的回答以获得更多详细信息),但是如果您确实通过了任何模式, 然后 您必须传递 in
或 out
或同时传递两者,因为不会将强制模式添加到您指定的模式(或失败指定)。
这是我阅读 Apache 文档的方式,来源支持我的观点,至少对于我的实现是这样。由于所有这些都在模板代码中,您可以查看来自不同编译器的 header 以了解它如何处理这些情况。因此,请查看 VS header ,查找 basic_fstream
并查看其方法是如何实现的。
缺少编译错误
otherwise, this code wouldn't compile.
您的代码打开一个仅用于输出的双向流,然后尝试从中输入内容。没有理由不能编译。流的静态类型是fstream
,即双向。只有在运行时,您才将具有特定含义的特定标志传递给构造函数。编译器(通常)不会对此进行检查,因此当您的代码无法从流中实际读取时,它会因此在运行时出现错误。
请注意,我不确定 Windows 是否真的支持打开文件仅供输出。 可能操作系统支持的唯一文件模式是只读和读写。 (请注意,我只是在这里推测。)在那种情况下,即使在运行时打开文件仅供输出并随后从中读取也不会成为问题,因为用 out 打开文件没有区别
或 in|out
。为了可移植性,应该选择正确的模式,因为那里有支持只写文件的内核。
关于c++ - 双向文件声明不隐式设置标志是否正确?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14590836/