tags:

views:

35

answers:

2

Hi!

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

A: 

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.

Jonathan Grynspan
A: 

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.

R..