Question:
What does this C code do?
Man and Mystery
2013-04-10 19:46:17 UTC
We are doing basic C programs in OS class to learn about processes and such, and I was asked to explain what the following program does but i have no idea where to begin understanding it. The first program is:

//bufferout.c
#include

int main(void) {
fprintf(stdout, "a");
fprintf(stderr, "a has been written\n");
fprintf(stdout, "b");
fprintf(stderr, "b has been written\n");
fprintf(stdout, "\n");
return 0;
}
with output of: "a has been written
b has been written
ab"


//bufferinout.c
#include

int main(void) {
int i;
fprintf(stdout, "a");
scanf("%d", &i);
fprintf(stderr, "a has been written\n");
fprintf(stdout, "b");
fprintf(stderr, "b has been written\n");
fprintf(stdout, "\n");
return 0;
}
with output of: "a"

can anyone tell me what is happening?
Three answers:
Michael
2013-04-10 21:21:51 UTC
The program is attempting to illustrate the the way in which the stdout and stderr file streams are buffered by default.



Assuming that the output of your program is directed to a terminal then stderr will be unbuffered (meaning that anything written to stderr will be written immediately) and stdout will be "line buffered" (meaning that anything written to stdout will be buffered and only written to the terminal when an end-of-line character is written).



This explains why the output of the program appears in the order that it does.

The strings written to stderr appear immediately, but the "a" and "b" strings written to stdout do not appear until the string containing the end-of-line character "\n" is written.
Key
2013-04-10 20:09:41 UTC
bufferout.c



#include is a pre-processor statement, at compile time it will find that file and include it. This will give you access to the "standard input output" functions like fprintf, etc.



In C the first letter of a statement often defines what the function deals with. fprintf will print to a file that file is determined by the first arguement and the second argument is what is to be printed. Return 0 is the exit status.



Samething for bufferinout.c but it is reading input from the user.
?
2016-12-15 09:26:14 UTC
that's real that in case you create an empty C++ console venture and manually rename your cpp report to offer it .c extension, seen Studio *will* execute the Microsoft C compiler, even nevertheless that's a doubly-out of date 1989 C compiler. Microsoft deserted C an prolonged time in the past. in case you decide directly to stay with this IDE and carry mutually C, substitute the underlying compiler. Intel C/C++ is a sturdy selection.


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Continue reading on narkive:
Loading...