使用in和out的ifstream和ofstream或fstream [英] ifstream and ofstream or fstream using in and out

查看:206
本文介绍了使用in和out的ifstream和ofstream或fstream的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在处理文件时,以下两个示例中的哪一个是首选? 一个提供比另一个更好的性能吗?有什么区别吗?

When dealing with files, which of the two examples below is preferred? Does one provide better performance than the other? Is there any difference at all?

ifstream input("input_file.txt");
ofstream output("output_file.txt");

vs

fstream input("input_file.txt",istream::in);
fstream output("output_file.txt",ostream::out);

推荐答案

在性能方面,这种情况下的差异可能很小.充其量您可以节省一点内存.

Performance-wise, there are probably only negligible differences in this case. At best you're saving a little memory.

重要的是,第一种情况有助于语义:std::fstream可以在输入,输出或同时在两者中打开.因此,您需要检查声明以确保在使用std::ifstreamstd::ofstream时将清楚您在做什么.第二种情况有更多的人为错误余地,这就是为什么应该避免这种情况.

What matters is that the first case helps with the semantics: a std::fstream could be opened in input, output or both. Because of this you need to check the declaration to be sure while using std::ifstream and std::ofstream will make it clear what you're doing. The second case has more room for human error which is why it should be avoided.

我自己的经验法则是在需要对文件进行读写访问的情况下(仅在这种情况下)使用std::fstream.

My own rule of thumb is to use a std::fstream when you need both read and write access to the file and only in this case.

这篇关于使用in和out的ifstream和ofstream或fstream的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆