C++ 不追加到文本文件

C++ Doesn't append to the text file

本文关键字:文本 文件 追加 C++      更新时间:2023-10-16

由于某种原因,下面的代码没有将user附加到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循环将读取整个文件,并在追加文件之前有效地将指针定位到文件末尾。

参见:这个问题。

PS:这看起来是一个错误:

if (found != std::string::npos) {
    std::cout<<"User already exists"<<std::endl;
    return;
}

如果usernameline的子字符串呢?

设置myfile.tellg (0)从文件开头开始读取。