Search code examples
cfileprintfbackspace

Why BACKSPACE (\b) does not work as intended with a file?


I opened a (text) file, like so: File *fp = fopen("findPattern2.txt", "w+"); in which i have written text. The last character i have in there is a ,. Now i want to delete that character using backspace. I've read the answers here that BACKSPACE only moves the cursor, then i have to overwrite that character by writing on top of it and this is what i do. So I did fprintf(fp, "\b \b") to completely erase the ,, but instead this is what the file shows afterwards:,BS BS. All of these work with a terminal. Why not with a file?

From what I gather the only way to do this to a file would be if i memory mapped it, edit its contents, copy them to a new file and delete the old one.


Solution

  • A file is just a collection of bytes that when read in by a program produce (possibly) meaningful results like a picture or video or whatever. Unless the program knows that a backspace character should delete the proceeding character, it won't do anything.

    Your terminal is a program that has been written in just that way to react to special characters like backspace and knows what to do when it receives one though.