Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

159
Visualizações
Can printf write to terminal without flushing stdout?
#include <stdio.h>

int main(){
 char a[2] = {0};
 a[0] = 't';
 printf("%s", a);

 scanf("%c", a);
 return 0;
}

scanf here will cause an automatic flush of stdout. Running a.out will print t on the terminal before running scanf, more info: How is printf getting flushed before scanf is executed?

However, doing a.out > out.txt and terminating it with ^C does not print anything inside out.txt yet the output still appeared on the screen without redirecting stdout with >.

If stdout is being flushed then why out.txt is still empty? If it's not being flushed then how did t appear on the screen in the first example?

(I know using \n or a manual fflush or properly terminating the program will fix the issue, i'm just curious about this behaviour).

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

The key is the word interactive:

The input and output dynamics of interactive devices shall take place as specified in 7.21.3.

As soon as you redirect the standard output to a file, it is no longer interactive.

For example the Linux C standard library actually executes the analogue of the isatty library call to figure this out. If it figures out that standard output is not directed to file it will also break this relationship. It will also increase the I/O performance of programs that work as part of a command pipeline.


You can yourself test whether stdout is connected to a terminal by executing

#include <unistd.h>

printf("stdout is connected to a terminal: %d\n", isatty(fileno(stdout)));
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda