Unexpected behaviour using escape codes in C

Viewed 69

I am currently trying to create a 'screen' in the console so that whenever the screen is refreshed it is cleared and then re-drawn; an example would be a program like Vim.

So far, I have used escape codes to clear the screen and then reposition the cursor after drawing some row markers. However, when this process is looped, the row markers get drawn below the previous ones, rather than in the same position again.

So if I draw 24 row markers each on a newline, then refresh the screen, I end up with 48 row marks each on a new line, rather than just the row markers in the same position again.

I have provided the example code:

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>

void drawRows()
{
  for(int i = 0; i < 24; i++) write(STDOUT_FILENO, "~\r\n", 3);
}
void refreshScreen()
{
  write(STDOUT_FILENO, "\x1b[2J", 4);
  write(STDOUT_FILENO, "\x1b[H", 3);

  drawRows();
  
  write(STDOUT_FILENO, "\x1b[H", 3);
}

int main()
{
    while(1) {
        refreshScreen();
        getchar();
    }
    return 0;
}

You can run it, enter some text and press enter. I think this should redraw the ~s in the same position but they just get get drawn below.

What am I doing wrong?

1 Answers

but they just get get drawn below

I guess the behavior you are describing is related that your process is "stuck" on getchar(), so the loop is not executing, because the input is line buffered. You have to set the terminal to raw mode first.

A 10 second google search resulted in https://viewsourcecode.org/snaptoken/kilo/index.html this link, which looks like a good introduction.

Related