以二进制模式打开 ifstream 是否需要 ios::in ?
这两者有什么区别? in
标志对象不是多余的吗?谢谢。
std::ifstream file1("one.bin", std::ifstream::in | std::ifstream::binary);
std::ifstream file2("two.bin" ,std::ifstream::binary);
What's the difference between these two? Isn't the in
flag object thing redundant? Thanks.
std::ifstream file1("one.bin", std::ifstream::in | std::ifstream::binary);
std::ifstream file2("two.bin", std::ifstream::binary);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
来自
ifstream
类构造函数的文档:因此,当从文件中读取时,我会使用 std::ifstream::in 标志,不是因为它是必需的(或不是),而是因为让编程接口知道您要执行的操作是一种很好的编程实践。将使用它。
编辑:
以下内容摘自http://www.cplusplus.com/doc/tutorial/files/< /a>,关于
open()
成员函数(但是问题中代码中的构造函数可能调用open()
复制模式标志而不进行修改)。尽管如此,网络上的许多示例在显示
ifstream
对象的构造时都使用ifstream::in
。可能真的是某种迷信行为,而不是编程行为。From the docs on
ifstream
class constructor:So when reading from a file, I would use
std::ifstream::in
flag not because it's required (or not) but because it would be a good programming practice to let a programming interface know what you are going to use it for.Edit:
The following is taken from http://www.cplusplus.com/doc/tutorial/files/, about
open()
member function though (but the constructors in the code in the question probably callopen()
copying the mode flags without modification).Nevertheless, many examples over the Web use
ifstream::in
when showing a construction of anifstream
object. Could really be some kind of a superstition practice, instead of a programming one.binary
,在这种情况下,仅指读取或写入的方法。在 Windows 上的常规模式下,'\n'
被转换为'\r''\n'
。这会影响读取和写入,因此二进制模式会将其关闭。out|binary
与in|binary
一样有意义binary
, in this case, only refers to the method of reading or writing. In regular mode on windows,'\n'
is translated to'\r''\n'
. This can affect both reading and writing, so binary mode turns this off.out|binary
makes just as much sense asin|binary
我在网上找不到权威文档。
编辑我什至无法在我的副本Josuttis Book,第 8 次印刷。 它应该在第 13.9 节第 627-631 页
经验证据表明它是多余的,IFF std::ios::in 或 std::ios:out 都没有通过:
成功:
显示相同哈希总和。
将失败(零字节输出)
I can't find authoritative documentation online.
Edit I can't even find a proper reference in my copy the Josuttis Book, 8th printing. It should have been in section 13.9 pp. 627-631
Empirical evidence suggests it is redundant IFF none of std::ios::in or std::ios:out are passed:
Succeeds:
show the same hash sum.
will fail (zero bytes output)
从 cplusplus.com 参考页面来看,没有区别。
ofstream
也是如此。因此,您不需要为ifstream
设置std::ios::in
或为std::ios::out
设置>ofstream,即使您设置了std::ios::binary
并忽略了in/out
模式。From cplusplus.com reference page, there is no difference.
It's the same for
ofstream
. Therefore, you don't need to setstd::ios::in
forifstream
orstd::ios::out
forofstream
, even if you have setstd::ios::binary
which omits thein/out
mode.