循环检查文件是否存在并对其进行处理

Loop to check existence of file and process it

本文关键字:处理 检查 文件 是否 存在 循环      更新时间:2023-10-16

我正在开始学校作业的第一部分,我必须提示用户输入文件名,检查文件是否存在,如果存在,则打开它进行处理;否则,我将让用户输入另一个文件名。

当我编译并运行下面的程序时,我收到错误消息"不存在文件。请输入其他文件名。当我输入不存在的文件的名称时,它只会再次运行我的 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
}