如何删除文本文件C++中的最后一个字符

How to remove last character in text file C++

本文关键字:C++ 最后一个 字符 文件 文本 何删除 删除      更新时间:2023-10-16

我有一个文本文件,我在其中写入用户输入的前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 iteratorsstringsboth进行相同操作。