C++ 不 append 到文本文件

标签 c++ file text append

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

另请参阅: this question .

PS:这看起来是个错误:

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

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

关于C++ 不 append 到文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25382373/

相关文章:

python - 使用 Boost/Python 的 undefined symbol

python - 如何在 python 代码中创建文件(如果可用,则默认为文本文件)

text - 使用文本编辑器将多行转换为单行

python - 为什么我的 Python 脚本没有将最后几行写入我的文件?

search - IntelliJ 文件掩码不适用于简单的排除文件模式!为什么?

java - 如何将 5 个字母的单词传输到新的文本文件中?

c++ - 返回对特定大小数组的引用,而不在返回类型中明确说明大小

c++ - 什么是 undefined reference /未解析的外部符号错误以及如何修复它?

c++ - gets() 二维数组

file - 简单 Bash - for f in *