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";
    }
}
Edit
I removed the std::ios_base::appendand 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();
    ...
 
     
     
    