c - 使用\r 覆盖标准输出中的上一行

标签 c linux printing

所以通常当我想在终端的前一行打印一些内容时,我只需这样做:

printf("\rprint a number %d", number);
fflush(stdout);

因此,对于我正在编写的程序,我想这样做并尝试过:

printf("\r%s - %s", buffer1, buffer2);
fflush(stdout);

哪里

buffer1, buffer2 = malloc(sizeof(char)*100);

但这不起作用,它每次都会换行打印。我假设这与我使用 char* 而不是 char[100] 或它们的大小有关?

示例输出(为简单起见,从代码中删除了颜色):

sample

编辑: buffer_1 从 stdin 填充到不同的线程中:

while (true) {
    system("/bin/stty raw");
    c = getchar();
    system("/bin/stty cooked");
    if (c == ' ') {
        return;
    }
    // check if input is not to long
    if (i == MAX_INPUT_LENGTH) {
        return;
    }
    // Get the latest added char and add to buffer
    t_a->input_buffer[i] = c;
    i += 1;
}

并且 buffer_2 被分配来自 system(find) 命令的输出:

 FILE *fp = popen("find -name a ", "r");
 char temp_buf[1024];
 // Get output of find command
 int i = 0;
 while (fgets(temp_buf, sizeof(temp_buf), fp) != 0 && i < MAX_NUM_RESULTS) {
     strcpy(result_buffer[i], temp_buf);
     i += 1;
 }

pclose(fp);

任何提示表示赞赏。

最佳答案

问题确实是 system(find) 的输出在结果末尾包含换行符。我通过不复制最后一个字符解决了这个问题:

 strncpy(result_buffer[i], temp_buf, strlen(temp_buf)-1);

感谢评论给我指出!

关于c - 使用\r 覆盖标准输出中的上一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58120689/

相关文章:

c - 为什么使用 "register"关键字会使我的代码更快?

c - Node* root 和 Node *root 的区别

c++ - 在 DLL 中的哪里调用 LoadLibrary?

linux - Linux 中文件的自动合并(一种方式)

linux - 内核中的奇怪锁定

node.js - 无法将新的 Azure Functions 部署到 Linux 应用程序

c - 如何在 asn1c 中使用封装的结构? (使用包含)

java - 是否可以将多个pdf页面合并为一张pdf并以java打印?

linux - awk:选择文本并使用它

c++ - 打印给定范围内的所有回文数