繁体   English   中英

C ++不会追加到文本文件

[英]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;
}

如果usernameline的子字符串怎么办?

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM