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

标签 c++ file

我不知道它是否相关,但我使用的是 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++检查文件是否存在,如果存在,改变输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20504952/

相关文章:

c++ - reinterpret_cast<volatile uint8_t*>(37)' 不是常量表达式

c++ - 标准容器元素类型和std::allocator类型不一样是不是错了?

c++ - 如何在 Windows 上紧密打包结构?

python - 如何在 bcc64 项目中嵌入 python?

c - 如何在 C 中每 3 个字符后添加一个换行符?

linux - 无法删除攻击者留下的文件$$$222.php

C++ 成员在删除后可用吗?

Excel - 超链接到与 xlsx 文件位于同一目录中的文件

c - 制作简单的设置文件时遇到问题

java - Ant + 保留控制值