-1

I have this function that reads from a tcp socket, but after I print the incoming message, no characters get printed in the printf() that follows, apart from the newline characters though for some reason.

void listenThread(void* context){ //context is a struct containing some userdata
  printf("started listener thread\n");
  struct clientdata *clientdata  = context;
  char* buff[128];
  for (;;){
    bzero(buff, sizeof(buff));
    read(clientdata->sockfd, buff, sizeof(buff));
    printf("\r%s", buff);
    printf("\n\n[%s]> ", clientdata->username); //the two \n's get printed but the rest after doesn't.
  }
}

I'm totally stumped and I'm convinced that the issue is glaringly obvious. Can anyone point me in the right direction?

Anirban166
  • 3,162
  • 4
  • 11
  • 27
SamBkamp
  • 65
  • 7
  • Does adding `\n` after `%s` or `[%s]` help? – kuro Dec 19 '19 at 09:02
  • 8
    `buff` is an array of *pointers* to characters, I think you meant `char buff[128];` instead. – Some programmer dude Dec 19 '19 at 09:02
  • You should ALWAYS check return value of reading functions (for a TCP socket I would use `recv()`). It returns -1 in error cases, and this is very important because `errno` value helps you to detect for exomple remote socket closures. – Roberto Caboni Dec 19 '19 at 09:05
  • @kuro adding a `\n` after the `[%s]` (`printf("[%s]>\n", clientdata->username);`) seems to do the trick and now the `[%s]` thing prints, however I would like it not to end in a \n. I also tried a nulll byte `\0` but that just brought me back to the same issue. – SamBkamp Dec 19 '19 at 09:09
  • @Someprogrammerdude BobRun, I tried it and I still have the same problem, seems Kuro might be on the right track though? – SamBkamp Dec 19 '19 at 09:11
  • 1
    `stdout` is probably line buffered. You could try using `fflush` after the `printf` or setting `stdout` unbuffered (set `setvbuf`). – AProgrammer Dec 19 '19 at 09:16
  • Does this answer your question? [Why does printf not flush after the call unless a newline is in the format string?](https://stackoverflow.com/questions/1716296/why-does-printf-not-flush-after-the-call-unless-a-newline-is-in-the-format-strin) – Sander De Dycker Dec 19 '19 at 09:20

1 Answers1

4

By default output to stdout (which is where printf writes) is line-buffered. That means output is actually written to the terminal when

  1. The buffer is full
  2. The buffer is explicitly flushed with the fflush function
  3. Or when you print a newline

That's why it seems to work when you print a newline, the buffer is actually written to the terminal.

If you don't want to print the newline, you could explicitly flush the buffer using fflush(stdout).


And you should really fix that array issue.

Some programmer dude
  • 363,249
  • 31
  • 351
  • 550
  • I didn't know that about stdout, this makes a lot more sense. It works now, thank you. Also, just for your peace of mind I have fixed the array issue ;) – SamBkamp Dec 19 '19 at 09:19