使用一个 ifstream 变量读取多个文件
为什么不能使用一个 ifstream 变量来打开一个文件,读取它,然后关闭它,然后打开另一个文件,读取和关闭等等? 这在代码中看起来如何(假设每个文件里面都有一个整数):
int k, l;
ifstream input1;
input1.open("File1.txt");
input1 >> k;
input1.close();
input1.open("File2.txt");
input1 >> l;
input1.close();
我解决问题的唯一方法是创建另一个 ifstream 变量。
Possible Duplicate:
C++ can I reuse fstream to open and write multiple files?
why is it not possible to use one ifstream variable for opening one file, reading it, then closing it and, after that, opening another file, reading and closing, etc?
How would that look in code (let's just say each file has an integer inside):
int k, l;
ifstream input1;
input1.open("File1.txt");
input1 >> k;
input1.close();
input1.open("File2.txt");
input1 >> l;
input1.close();
the only way I solved the problem was creating another ifstream variable.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以使用相同的变量,在重用之前需要调用
.clear()
来清除对象的标志:但我建议您不要重用它们。如果您不想同时存在多个变量,则可以将每个变量保留在其自己的范围内:
You can use the same variable, you need to call
.clear()
to clear the object's flags before you reuse it:But I recommend instead you don't reuse them. If you don't want to have more than one variable around at once, you can keep each one in its own scope:
在
ifstream
对象上的close()
之后调用clear()
Invoke
clear()
afterclose()
onifstream
object问题的原始代码效果很好:
注意,来自 C++0X (C ++11) 上,无需调用
basic_ifstream::clear()
因为标准指定(请参阅 C++0x/27.9.1.9)成功basic_ifstream::open()
应调用basic_ifstream::clear()。The original code from the question works well:
Note, from C++0X (C++11) on, there is no need to call
basic_ifstream::clear()
because the standard specifies (see C++0x/27.9.1.9) successfulbasic_ifstream::open()
shall callbasic_ifstream::clear()
.虽然完全可以按照您的建议进行操作(尽管如果提取失败,您可能需要清除流的错误标志),但它并不是非常优雅。在 C++ 中,您应该在需要时随意创建新对象,并在完成后丢弃它们。也许编写此代码的更系统的方法是在本地循环范围内:
您当然可以将循环逻辑替换为更适合您的情况的任何其他内容。例如,根据零一多规则,您可能在某个地方有一个包含候选文件名的容器;或者您可能会循环遍历命令行参数。
While it's entirely possible to do what you suggest (though you may need to clear the stream's error flags if the extraction failed), it's not terribly elegant. In C++, you should feel free to make new objects when you need them, and discard them when you're done. Perhaps a more systematic way to write this code is in a local loop scope:
You can of course replace the loop logic by anything else that's more appropriate to your situation. For example, according to the Zero-One-Many rule, you might have a container somewhere that contains your candidate filenames; or you could be looping over command-line arguments.