如何删除文本文件C++中的最后一个字符
How to remove last character in text file C++
我有一个文本文件,我在其中写入用户输入的前10个字符:
int x=0;
ofstream fout("out.txt");
while (x<=10)
{
char c=getch();
if (c==8)//check for backspace
fout<<'b';
else
fout<<c;
x++;
}
每当用户按下退格键时,我都想从文本文件中删除以前输入的字符。
我尝试将'b'
写入文件,但它没有删除最后一个字符。
我该怎么做?
感谢
如果我理解正确,您的要求是BS应该将文件指针向后移动一个位置。这正是seekp
的作用。
在windows中(由于getch…)以下内容刚好满足要求:
int x=0;
ofstream fout("out.txt");
while (x<=10)
{
char c=getch();
if (c==8) { //check for backspace
fout.seekp(-1, std::ios_base::end);
if (x > 0) x -= 1; // ensure to get 10 characters at the end
}
else {
fout<<c;
x++;
}
} return 0;
它在这里工作,因为最后一个字符被覆盖。不幸的是,正如另一个问题所证实的那样,没有用fstream
截断打开的文件的标准方法。
在C++中,没有简单的方法可以删除文件的最后一个字符。你必须走琐碎的路
Read the contents of the file except the last one & copy it to another file
您可以使用input-output iterators
或strings
或both
进行相同操作。
相关文章:
- lower_bound()返回最后一个元素
- 获取向量C++中第一个值和最后一个值的和
- 获取用C/C++打印的最后一个字符串
- 使用运算符 [] 引用 std::vector 上最后一个元素时出现问题<>
- 为什么这个程序返回最后一个单词而不是最长的单词?
- 为什么我的最后一个 ELSE 条件无法正确执行
- Lower_bound不适用于具有 3 个元素的向量的最后一个元素
- 查找数组中第一个最小值和最后一个最大值元素之间的算术平均值
- 仅显示链表的最后一个元素
- 测试迭代器是否位于列表中的最后一个
- push_back通过自行创建的对象获取最后一个元素的向量
- 使用 map.end() 访问 map 的最后一个元素
- 如何知道地图中的最后一个元素是否被删除?
- std::矢量保存 只推送最后一个元素
- 反转后不返回最后一个元素
- 如何删除矢量中的重复值,最后一个除外
- 如何在写入文件时擦除最后一个逗号
- 如何在新数组较小时创建新数组并将旧数组的最后一个元素复制到新数组中?
- 在 QListView 中显示最后一个元素
- 如何获取 std::filesystem::p ath 中的最后一个目录?