m0bi5
m0bi5

Reputation: 9472

How to remove last character in text file C++

I have a text file into which I write first 10 characters the user inputs:

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++;
}

Whenever the user presses backspace I want to delete the previously entered character from the text file.

I tried writing '\b' to the file but it doesn't delete the last character.

How can I do so?

Thanks

Upvotes: 1

Views: 4788

Answers (2)

Serge Ballesta
Serge Ballesta

Reputation: 149075

If I correctly understand, your requirement is that a BS should move the file pointer one position back. That's just what seekp is done for.

In windows (because of getch...) the following just meet the requirement:

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;

It works here because the last character is overwritten. Unfortunately, as this other question confirms, there is no standard way to truncate an open file with fstream.

Upvotes: 1

Ankit Acharya
Ankit Acharya

Reputation: 3111

There's no simple way by which you can delete the last character of the file in C++. You have to go the trivial way ie :-

Read the contents of the file except the last one & copy it to another file

You can either use input-output iterators or strings or both for the same.

Upvotes: 0

Related Questions