[英]C++ Doesn't append to the text file
由於某些原因,下面的代碼不會將用戶追加到user.txt文件中。 它總是以if(file.fail())
結構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
-loop會讀取整個文件,並在將其追加到文件之前有效地將指針定位到文件的末尾。
另請參閱: 這個問題 。
PS:這似乎是一個錯誤:
if (found != std::string::npos) {
std::cout<<"User already exists"<<std::endl;
return;
}
如果username
是line
的子字符串怎么辦?
將myfile.tellg (0)
從文件的開頭開始讀取。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.