Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 413
  • Last Modified:

Delete last character in a file

Hello, I am writing a simple text editor and would like to figure out how to delete the last character in a file that I am writing to.  Right now when I hit backspace, in the dos window it moves back a character but in the text file I just get a big .  Here is my source so far so you can understand how this file is being written to:

void input_text()
{
     // Initialize variables and open file for writing
     char ch;
     ofstream textfile("textfile.txt");

     // Read in characters and store to file
     while (ch != ESC)
     {
          ch = getch();
          if (ch != ESC)
          {
               if (ch == ENTER)
                    ch = '\n';
               textfile << ch;
               cout << ch << flush;
          }
     }
     
     // Close file
     textfile.close();    
     
}

I can read in backspace just like I can enter and esc but I don't know how to move one space back in the file.  Any help would be appreciated!
0
regan_a
Asked:
regan_a
  • 2
1 Solution
 
KocilCommented:
It is strange to make an editor that directly write into the file. But here is the solution you ask

  while((ch = getch()) != ESC) {
      switch (ch) {
        case BACKSPACE:
           textfile.seekp(textfile.tellp()-1);
           cout << BACKSPACE << ' ' << BACKSPACE;
           break;
        case ENTER : ch = '\n';
        default:
              textfile << ch;
              cout << ch << flush;
      }
  }


Thing will be easier if you buffer the input before write it to the textfile. For example
 
   char buffer[100;
   
   while(...) {
     gets(buffer);
     textfile << buffer;
   }




0
 
akshayxxCommented:
>>>I am writing a simple text editor
then its better that u should use the buffer method.. load the file in -inmemory buffer do the changes and then save the buffer back to the file

editing straight to the file is nuthing but strange..
0
 
regan_aAuthor Commented:
Oh, I know it is strange, I just wanted to see if it could be done :)  Regularly I would load it into the buffer but I am learning the language and trying to imagine as many abstract ways of learning different things as possible.  Anyways, thanks for the help/advice you two.
0
 
akshayxxCommented:
small note--
almost anything can be done in programming world.. and somethings are preferred over most others
0

Featured Post

Become an Android App Developer

Ready to kick start your career in 2018? Learn how to build an Android app in January’s Course of the Month and open the door to new opportunities.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now