C++检查文件是否存在,如果存在,则更改输出

C++ check if file exists, if yes, change output

本文关键字:存在 输出 如果 是否 检查 C++ 文件      更新时间:2023-10-16

我不知道它是否相关,但我使用的是Windows 7和Microsoft Visual Studio 2010。

我想做的就是向用户询问文件名,检查该名称的文件是否存在,当它确实存在时,向他们询问不同的

我的尝试

Main.cpp

std::cout << std::endl << "You must create a username" << std::endl;
std::cin >> username;
user.checkFile(username);

用户.cpp

void User::checkFile(std::string &username)
{
std::ifstream fin (username + ".txt");
    while (fin.good)
    {
    std::cout << "This username already exists, please choose another.";
    std::cin >> username;
     if (fin.bad)
        {
            break;
            fin.close();
        }
    }
}

这正确地识别了该名称的文件是否存在,但即使我键入了不存在的名称,它仍然会"告诉"我它确实存在

Main.cpp

std::cout << std::endl << "You must create a username" << std::endl;
do
{
    std::cin >> username;
    if (user.checkFile(username))
        break;
    std::cout << "This username already exists, please choose another." << std::endl;
}
while (true);

用户.cpp

bool User::checkFile(const std::string &username)
{
    FILE *fin = fopen((username + ".txt").c_str(), "r");
    if (fin)
    {
        fclose(fin);
        return false;
    }
    return true;
}

我会使用简单的C函数来处理文件。

void User::checkFile(std::string &username)
{
    std::string username2 = username + ".txt";
    FILE * f = fopen(username2.c_str(), "r");
    while (f != NULL)
    {
      fclose(f);
      std::cout << "This username already exists, please choose another.";
      std::cin >> username;
      std::string username2 = username + ".txt";
      f = fopen(username2.c_str(), "r");          
    }
}

这样,在函数cal返回后,yout变量username将保持有效的名称,因为您是通过引用传递它的。

int main(void) {
    bool fileExists = true;
    while (fileExists)
    {
            string fileName;
            cout << "Enter file name: ";
            cin >> fileName;
            ifstream ifs(fileName.c_str());
            fileExists = !ifs.good();
    }
    return 0;
}

如果您将自己限制为Windows,则有一个API函数可以做到这一点:PathFileExists

如果你想坚持使用标准库,你可以做以下事情:

string filename;
cin >> filename;
ifstream fin(filename);
if (fin.is_open())
{
    // file opened successfully
}
else
{
    // file did not open
}

输入新字符串后,您需要重新打开名称为的文件

std::cout << "This username already exists, please choose another.";
std::cin >> username;
fin.close();
fin.open(username);

此外,goodbad是必须使用呼叫运算符()来调用的函数。

我认为您需要使用c_str()函数转换字符串。例如:

string a="df";
a.c_str(); // will return c string