clinuxnewlinebackspace

C - Remove a newline character that has already been printed


How can I remove a newline character that has already been printed and loaded onto the buffer? As far as I know, the \b character only moves the cursor back in the current line, and doesn't work with newline characters. How can I get around this?

It would be helpful if the question were edited to indicate how this undesirable newline was emitted. – Mahonri Moriancumer

It is actually not undesirable. I want to preview the user with one state of the buffer, before outputting the other one. I do not however, want to continuously display multiple buffer-states. For instance, say I want to display two matrices,

1 1 1 1
1 1 1 1
1 1 1 1
1 1 1 1

and

0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0

I want the second matrix to replace the first one. To do this, I need to remove the first matrix's outputted numbers.

Perhaps you might consider editing your question again and indicating the OS and/or terminal type?

Currently running Linux (Ubuntu) x64, using xterm (ROXTerm to be exact).


Solution

  • There are two widely-supported characters for writing over things that have been written earlier: \b, backspace, as you mentioned, and \r, carriage return, to bring the ‘write head’ back to the start of the line.

    If you want to go back to a previous line, you’re not completely out of luck, but you’ll have to resort to something that, while still widely supported, particularly by terminal emulators, may not be quite so widely supported (e.g., it probably wouldn’t work if you were to pipe it to lp). I am referring to ANSI escape sequences. There’s plenty, but of note for you is ^[[A, which moves the ‘write head’ up one line. (^[ here is the ESC ASCII character, hex value 0x1B). To use it in C:

    printf("\x1B[A");  /* move up one line */