Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
276 views
in Technique[技术] by (71.8m points)

Clearing output of a terminal program Linux C/C++

I'm interested in clearing the output of a C program produced with printf statements, multiple lines long.

My initial guess was to use

 printf("output1
");
 printf("output2
");
 rewind(stdout);
 printf("output3
");
 printf("output4
");

but this produces

 output1
 output2
 output3
 output4

I was hoping it would produce

 output3
 output4

Does anyone know how to get the latter result?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can have the desired result both for terminal and pipes if you remember to remove the control characters as well. This is hardcoded for two lines.

#include <stdio.h>

int
main ()
{
    fputs("output1
",stdout);
    fputs("output2
",stdout);
    fputs("33[A33[2K33[A33[2K",stdout);
    rewind(stdout);
    ftruncate(1,0); /* you probably want this as well */
    fputs("output3
",stdout);
    fputs("output4
",stdout);
    return 0;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...