Reputation: 5
For some reason, the code below doesn't append the user to the user.txt file. It always ends up in the if(file.fail())
structure.
Any idea on how to fix it? I tried closing and opening the same file again before writing the user to it. But that doesn't seem to work either.
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";
}
}
I removed the std::ios_base::append
and added a couple lines: (it works like I want it to)
...
std::cout<<"functie:";
std::cin>>functie;
myfile.clear();
myfile.seekg(0, myfile.end);
user = "\n" + gebruikersnaam + " " + functie;
myfile << user;
myfile.close();
...
Upvotes: 0
Views: 616
Reputation: 17900
You're not rewinding the file, i.e. repositioning the read/write pointer to the beginning of the file. Using std::ios_base::app
means that the read/write pointer is position at the end of the file.
You should probably omit std::ios_base::app
. This way your while
-loop will read the whole file and effectively position the pointer to the end of the file before you append to it.
See also: this question.
PS: This looks to be a bug:
if (found != std::string::npos) {
std::cout<<"User already exists"<<std::endl;
return;
}
what if username
is a substring of line
?
Upvotes: 2