循环检查文件是否存在并对其进行处理
Loop to check existence of file and process it
我正在开始学校作业的第一部分,我必须提示用户输入文件名,检查文件是否存在,如果存在,则打开它进行处理;否则,我将让用户输入另一个文件名。
当我编译并运行下面的程序时,我收到错误消息"不存在文件。请输入其他文件名。当我输入不存在的文件的名称时,它只会再次运行我的 do while 循环的第一部分。我是C++的初学者,但我以前做过,我觉得它应该正常运行。任何帮助将不胜感激。
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
struct customerData
{
int _customerID;
string _firstName, _lastName;
double _payment1, _payment2, _payment3;
};
void processFile();
int main()
{
processFile();
system ("pause");
return 0;
}
void processFile()
{
string filename;
ifstream recordFile;
do
{
cout << "Please enter a filenamen";
cin >> filename;
recordFile.open(filename);
if (recordFile.good())
// {
// enter code for if file exists here
// }
;
}
while(recordFile.fail());
{
cout << "No file by that name. Please enter another filenamen";
cin >> filename;
recordFile.open(filename);
}
}
要检查文件是否已成功打开,您必须使用 std::fstream::is_open() 函数,如下所示:
void processfile ()
{
string filename;
cout << "Please enter filename: ";
if (! (cin >> filename))
return;
ifstream file(filename.c_str());
if (!file.is_open())
{
cerr << "Cannot open file: " << filename << endl;
return;
}
// do something with open file
}
成员函数 .good() 和 .fail() 检查其他内容,而不是文件是否成功打开。
我不是 100% 确定你在这里的意图是什么,但你明白你在这里只有一个循环吗? 在你的 do/while 循环之后,你在大括号中有一些代码,但这没有连接到任何循环结构......它只是一个新范围(在这里没有用处)。
因此,您的程序会这样做:
1)询问文件名。 尝试打开它。 如果可以读取文件流,请执行"在此处输入代码"部分。
2)检查文件流是否"坏"。如果是这样,请返回到步骤 1。 否则,请继续。
3)打印出"没有该名称的文件",提示输入新文件,尝试打开它
这几乎肯定不是你想要的。
你可以使用 c 代码。
FILE *fp = fopen("file" "r");
if(fp){
//do stuff
}
else{
//it doesnt exist
}
附带说明一下,当使用命名空间 std 时,请尝试使其不是全局的
必要时,您可以将其放在函数中
int main(){
using namespace std;
//other std stuff
}
相关文章:
- 如何处理来自核心指南检查器的关于gsl::at的静态分析警告
- 使用预处理指令检查是否包含标头?
- C++ 错误检查 fstream open() 命令和一般字符串流错误处理
- 如何检查和处理前提条件
- 为什么我的模板专业检查不足以正确处理相应的类型
- 数据文件处理中的错误检查是否可以打开文件 - 为什么会发生
- 检查信号处理程序是否不是默认值
- 在执行其中的代码之前,是否处理了 if 中的所有逻辑 OR 分隔检查?
- 如何在功能中的理智检查过程中处理整数的溢出
- 循环检查文件是否存在并对其进行处理
- 如何编写一个C++例程来检查我在键盘上按下了哪个键,以便我可以单独处理每个按键?
- 检查在ON_COMMAND_RANGE处理程序函数上单击了哪个按钮
- 从C++应用程序运行批处理脚本,并检查它是否具有无限循环
- C++:在构造函数>中进行健全性检查时,我是否需要/是否可以使用异常处理?
- 使用try-Catch异常处理程序和if-else条件检查之间的区别
- c++中未处理的异常检查
- 我如何检查和处理非常接近零的数字
- 检查write()/send()是否可以处理整个缓冲区而不阻塞,否则失败(没有部分写入)
- 如何处理已检查迭代器
- 如何检查 c++ 中是否存在记录(数据文件处理)