出于某种原因,下面的代码没有将 user append 到 user.txt 文件。它总是以 if(file.fail())
结构结束。
关于如何解决它的任何想法?在写入用户 之前,我尝试关闭并再次打开同一个文件。但这似乎也不起作用。
void users::userAdd()
{
std::string username;
std::string function;
std::string user;
std::size_t found;
std::string line;
std::fstream myfile ("C:\\Users\\kk\\Desktop\\users.txt", std::ios_base::in | std::ios_base::out | std::ios_base::app);
if (!myfile || !myfile.good())
{
std::cout << "could not open file!\n";
}
if (myfile.is_open())
{
std::cout<<"new username:";
std::cin>>username;
while (! myfile.eof())
{
getline (myfile,line);
found = line.find(username);
if (found != std::string::npos)
{
std::cout<<"User already exists"<<std::endl;
return;
}
}
std::cout<<"Function:";
std::cin>>function;
user = username+ " " + function;
myfile << user;
myfile.close();
}
if (myfile.fail())
{
std::cout << "Failed to append to file!\n";
}
}
编辑
我删除了 std::ios_base::append
并添加了几行:(它像我想要的那样工作)
...
std::cout<<"functie:";
std::cin>>functie;
myfile.clear();
myfile.seekg(0, myfile.end);
user = "\n" + gebruikersnaam + " " + functie;
myfile << user;
myfile.close();
...
最佳答案
您不是在倒回文件,即将读/写指针重新定位到文件的开头。使用 std::ios_base::app
意味着读/写指针位于文件末尾。
您可能应该省略 std::ios_base::app
。这样,您的 while
循环将读取整个文件,并在追加到文件之前有效地将指针定位到文件末尾。
另请参阅: this question .
PS:这看起来是个错误:
if (found != std::string::npos) {
std::cout<<"User already exists"<<std::endl;
return;
}
如果 username
是 line
的子字符串怎么办?
关于C++ 不 append 到文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25382373/