I have a similar issue to Update printf value on same line instead of new one but did not find a solution yet.
I want to output data from a file or sensor when it arrives. It contains several data fields in one line or structure. For simplicity, in this example I only output integers here instead of the data sets. I want to output the text over several lines and then update the values but not the labels (at least not visible to the user).
My two issues:
1) In function oneline(), the first line is not even visible because it is overwritten immediately. I put the sleep(1) there (commented out) but also then the output1 is not displayed. But only the second value is displayed, so I cannot overwrite the first value (or all values in that tupel that I have written in one line each to the terminal before). If I don't fflush(), then there is no output at all before the very last data set arrives.
If I add the fflush() after output1, then only "output1" is visible until the very last value arrives.
2) In function twolines(), I always get new lines written, surely because of the \n. So with that, I cannot go back one (or multiple) line(s) using \r. I thought I could cheat and use double-\r but that did not help.
So the output gets longer and longer instead of overwriting the existing output. But my aim is to keep the spot in where the output takes place small.
How can I solve it so that every output value stays in the same place and gets overwritten whenever a new value from file or sensor arrives? Do I always need to clear the terminal before I output the new set of values or is there a more elegant solution? Or is there a better command then printf()? Currently it is a console program but later it will become a GUI program.
Example code:
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdint.h>
#include <time.h>
void oneline();
void twolines();
int main(void)
{
printf("\n---oneline---\n");
oneline();
printf("\n---twolines---\n");
twolines();
}
void oneline()
{
for (int i=1;i<=5;i++)
{
printf("output1: %d\r", i);
// fflush(stdout);
// sleep(1);
printf("output2: %d\r", i);
sleep(1);
fflush(stdout);
}
}
void twolines()
{
for (int i=1;i<=5;i++)
{
printf("output1: %d\n\r\r", i);
// sleep(1);
printf("output2: %d\n\r\r", i);
sleep(1);
fflush(stdout);
}
}