在C中添加对换行符(\ n)的支持

时间:2016-02-24 11:40:14

标签: c

我编写了一个简单的操作系统,我在Linux中使用QEMU进行编译。终端在屏幕上打印一条简单的消息("Hello World\n"),然而,换行符(\n)产生一个奇怪的字符,而不是在消息后插入一个新行。

以下是我为putchar编写的代码:

void putchar(char c) {
    putentryat(c, color, column, row);
    if (++column == WIDTH) {
        column = 0;
        if (++row == HEIGHT) {
            column = 0;
        }
    }
}

主要功能只需调用writestring函数,该函数显示如下代码所示的消息。

void main() {
    initialize();
    writestring("Hello World\n");
}

目前n正在打印垃圾字符,因为程序不支持stdio.h。我在putchar('\n');之后尝试在putchar函数中添加putentryat(...),但我仍然遇到问题。

如果有人可以提供我如何解决这个问题的提示,我将不胜感激。

3 个答案:

答案 0 :(得分:4)

也许你需要这个:

void putchar(char c){
   if (c == '\n') {
     column = 0;
     if (++row == HEIGHT) {
        // perform scroll 
     }
   }
   else  
      putentryat(c, color, column, row);

   if (++column == WIDTH) {
     column = 0;
     if (++row == HEIGHT) {
       // perform scroll
       column = 0;
     }
   }
}

答案 1 :(得分:3)

// ...
if (c == '\n') {
    column = 0;
    row++;
    // do not putentry
}
// ...

答案 2 :(得分:3)

终端专门处理某些字符,例如\n,以执行特定任务:

  • \n会导致光标向下移动一行,并可能返回到最左侧的列(在您的情况下为column = 0)。
  • \r应该使光标移动到当前行的最左侧列。
  • \t将光标向右移动到下一个TAB停靠点,通常是8个位置的倍数。
  • \f可以擦除屏幕并将光标移动到原位。
  • \a可能会导致扬声器发出蜂鸣声或屏幕闪烁。

执行所有这些操作,而不是在当前光标位置显示字符。您必须专门测试字符值才能执行特殊操作,而不是显示字符。

以下是一个例子:

void term_putchar(int c) {
    switch (c) {
      case '\r':
        column = 0;
        break;
      case '\n':
        column = 0;
        row++;
        break;
      case '\t':
        column = (column + 8) / 8 * 8;
        if (column >= WIDTH) {
            column -= WIDTH;
            row++;
        }
        break;
      case '\f':
        term_erase_screen();
        column = row = 0;
        break;
      case '\a':
        term_beep();
        break;
      default:
        putentryat(c, color, column, row);
        if (++column == WIDTH) {
            column = 0;
            ++row;
        }
        break;
    }
    if (row == HEIGHT) {
        if (term_page_mode) {
            row = 0;
        } else {
            term_scroll_screen_up();
            row--;
        }
    }
    /* should update the blinking cursor on the screen screen */
}

int putchar(int c) {
    if (output_to_terminal) {
        term_putchar(c);
    } else {
        /* output to file? */
    }
    return c;
}

请注意,真实终端具有更多特殊字符来控制输出,屏幕处理,颜色,光标移动,流量控制等。除特定字符外,它们还使用转义序列(\e后跟其他字符)

相关问题