user3752929
user3752929

Reputation: 5

C++ Doesn't append to the text file

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();
    ...

Upvotes: 0

Views: 616

Answers (2)

Nati Spark
Nati Spark

Reputation: 1

Put myfile.tellg (0) to start reading from the start of the file.

Upvotes: 0

jotik
jotik

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

Related Questions