如何打开文件
How to opening files
我在打开文件时遇到了一些问题,所以有人能解释一下while循环是如何在这里工作的吗:
#include <fstream>
std::ifstream infile("thefile.txt");
int a,b;
while (file >> a >> b){}
while
循环有一个空的主体。因此,它所要做的就是计算表达式file >> a >> b
,直到它得到错误的
file>>a>>b
从您打开的文件中读取两个整数。如果遇到错误或文件结尾,则为false。
编辑:
但您在打开文件时提到了问题。在这里,你可以检查它是否成功,或者为什么失败:
if (!file)
cerr<<"Couldn't open the file:"<< strerror(errno) <<endl; // or alternatively
// use the good old perror()
else
...
实际上不清楚您在问什么。如何正确打开文件,或者while (file >> a >> b)
在无法正确打开文件时如何工作。
好吧,试着在评论中解释代码:
#include <fstream>
std::ifstream infile("thefile.txt"); // Tries to open the file in the current working
// directory the program is executed
int a,b;
while (file >> a >> b){} // Will try to read numeric values from file and store them to
// a and b. If the file couldn't be opened, or the parsing
// for numeric values failed, the loop will never be entered or
// immediately end
相关文章:
- 程序运行,但文件无法打开.C++中的命令行
- 文件无法打开
- Windows std::fstream 修改文件后打开()?
- ifstream说它打开了一个文件,但文件没有打开
- Qt自动生成的.rc文件无法打开包含文件'windows.h'
- Protobuf:无法在 message.pb.h 文件中打开包含文件 common.h
- DirectX 11 文件无法打开源文件
- Visual C 关闭文本文件和打开新的控制台窗口
- Open() 用于创建文件和打开现有文件.有人能分辨出其中的区别
- C 文件处理打开
- 当要读取的文件已打开时,文件读取进入无限循环
- 我应该在文件无法打开时关闭文件吗?
- boost::log关闭日志文件并打开一个新文件
- Curl在C 中下载的文件无法打开
- 使用xsdcxx树解析器的XSD到C++类.方法从文件中打开xml
- Cin.get() 在文件被打开后 ifstream.
- 如何知道文件已打开?.QT
- C++文件流打开模式不明确
- 文件无法打开进行写入
- C++ IF流文件已打开,但失败