0

it seems that escaped characters passed in write() don't work (at least) properly.

printf("test");
printf("\r1234);

return

123

as expected, but

printf("test");
write(1, "\r1234, 5);

return

1234test

so the line is not overwritten

I would like to know how to erase/overwrite a line in C (i am on linux btw) Thank you

lokoum
  • 71
  • 10

2 Answers2

2

Try flushing the output stream: Code:

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

int main()
{
    printf("test");
    fflush(stdout);
    write(1, "\r1234", 5);
    return 0;
}

Output:

1234
user156213
  • 736
  • 4
  • 12
  • a significant part of the problem is failing to include the appropriate header file for the system function 'write()' which for linux would be '#include ' – user3629249 Aug 18 '15 at 05:11
  • haha thanks, but couldn't you just have said "you forgot to include unistd.h"? – user156213 Aug 18 '15 at 09:01
2

Your REAL problem is that printf is buffered and write is immediate. And so the write goes first. Yes it does send the \r, the terminal reads it and moves to the front of the line. And when the program exits it flushes the STDOUT buffer and prints the printf contents.

Zan Lynx
  • 53,022
  • 10
  • 79
  • 131
  • thank you,I didn't know about this difference, but what is I have an infinite loop with printf ? it flushes the STDOUT each loop, right ? so printf also flushes stdout for the previous printf executed ? – lokoum Aug 17 '15 at 03:41
  • @lokoum Why would you believe that printf flushes the buffer? In fact, printf and other buffered IO functions are only guaranteed to flush the buffer when flush/fflush is called or when the program exits. – Zan Lynx Aug 17 '15 at 03:48
  • you can force a buffer output/flush by having the last two characters on the format parameter for the printf() be: '\n' – user3629249 Aug 18 '15 at 05:13
  • User3629249: That is the line buffering mode which does not apply to disk files or Windows consoles. – Zan Lynx Aug 18 '15 at 16:49