Oliver Hanappi
Oliver Hanappi

Reputation: 12336

How to buffer stdout until stdin is closed?

I'm making myself familiar with C programming and want to write a program similar to expand. The command line tool first reads every input from stdin, processes it and writes the complete result to stdout. How can I achieve this in an elegant manner?

Currently my code looks something like this. This works perfectly when processing files, but obviously when input is stdin after each newline entered by the user he immediately gets the result for the line entered.

char buffer[1024];
while (fgets(&buffer[0], sizeof(buffer) / sizeof(char), input) != NULL)
{
    /* do something */
    printf("output");
}

Best Regards,
Oliver Hanappi

Upvotes: 1

Views: 208

Answers (2)

R.. GitHub STOP HELPING ICE
R.. GitHub STOP HELPING ICE

Reputation: 215193

Write all of your output to a temporary file instead of stdout, then copy from this temporary file to stdout at the end of your program's execution.

Upvotes: 1

Jonathan Grynspan
Jonathan Grynspan

Reputation: 43472

Well, what makes you think stdin will ever close? :)

You can use isatty(STDIN_FILENO) to determine if stdin is hooked up to user input. (If it is, the function returns non-zero.) If that's the case, you can alter your behaviour accordingly.

Upvotes: 0

Related Questions