C++检查文件是否存在,如果存在,则更改输出
C++ check if file exists, if yes, change output
我不知道它是否相关,但我使用的是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);
此外,good
和bad
是必须使用呼叫运算符()
来调用的函数。
我认为您需要使用c_str()
函数转换字符串。例如:
string a="df";
a.c_str(); // will return c string
相关文章:
- 输出 [left]=input[i] 行中的 c++ 代码中存在无效的类型错误
- 在存在错误代码的情况下输出参数与 NRVO
- C++实现代码中的字符串不应存在于输出二进制文件中.如何解决
- 当存在一行时,Cppcheck 不会输出警告:auto lambda = [](){};
- 我的计划中存在什么问题?为什么无法显示最终输出
- 将输出图像保存在Caffe中
- 仅当c++中存在小数时,格式化浮点值的输出
- 如何仅在对象存在/特定情况下输出对象的某个部分?
- C++检查文件是否存在,如果存在,则更改输出
- 指针引用的值不再存在时输出冲突
- 如何将数字拆分为其数字并将它们相加,如果存在任何字符,则应"invalid input"输出?
- 即使输入文件不存在,也会继续创建输出文件?编辑****
- 嵌套 std::map 的输出存在问题
- 没有错误,但输出不正确.可能存在指针问题
- g++输出和Visual Studio输出之间存在差异.浮点变量
- 文件输出中存在错误字符
- 是否存在处理预处理器指令并给出实际预处理器输出的工具
- 输出错误.可能存在强度问题
- C++ 当存在“”时输出重复行
- Valgrind总结:输出中是否存在内存泄漏?