C++ 不追加到文本文件
C++ Doesn't append to the text file
由于某种原因,下面的代码没有将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;
}
如果username
是line
的子字符串呢?
设置myfile.tellg (0)
从文件开头开始读取。
相关文章:
- 文本文件中的单词链表
- 在C++程序中输入的文本文件将不起作用,除非文本被复制和粘贴
- 如何将内容数组写入文本文件?
- 无法通过空白将文本文件行分隔为矢量
- 我正在使用嵌套的while循环来解析具有多行的文本文件,但由于某种原因,它只通过第一行,我不知道为什么
- C++将文本文件中的数据读取到结构数组中
- 在指针的帮助下,文本文件中单词的频率
- 将字符指针十六进制转换为字符串并保存在文本文件C++中
- 将值从二维数组输出到文本文件
- 如何在c++中从文本文件中逐行读取整数
- 从文本文件中读取时钟时间和事件时间并进行处理
- 如何从文本文件中读取值和数组
- 如何在C++中确定文本文件中的元素是字符还是数字
- C++试图读取一个文件并输出到另一个文本文件
- 如何通过套接字将文本文件的内容从服务器发送到客户端
- 已修改的LinkedList未在文本文件本身中更新
- C++文本文件的获取线
- 为什么C++的文件 I/O 在读取文本文件时忽略初始空行?我怎样才能让它不这样做?
- 打印逐行存储的文本文件
- C++文本文件输入