FILE*
(a pointer to a
file) which are connected to devices where you can send data.
For every C-program there are always two output streams open: the standard
output stream, stdout
, and the standard error stream,
stderr
. By default both of these streams are connected
to the terminal from which the program is run. Anything you send to
these streams are by default shown on the terminal (however, these
streams can be easily redirected by your shell to other destinations,
see "note-redirect").
You send data to stdout
stream with the printf
function,
double x = 1.23; printf("%g\n",x);or, equivalently, with the
fprintf
function,
fprintf(stdout,"%g\n",x);
You send data to stderr
stream with the
fprintf
function, for example,
fprintf(stderr,"%g\n",x);
FILE* mystream = fopen("out.txt","w");where "w" means "writing" (read
man fopen
for details).
Now you can send data directly into file out.txt
by writing
into stream mystream
, for example,
fprintf(mystream,"%g\n",x);When you are done writing, you close the stream,
fclose(mystream);
stdin
, autmatically opened and connected to the terminal
from which the program is run (but can be conveniently redirected).
Apart from this you can also open your own file streams for reading,
for example,
FILE* mystream = fopen("input.txt","r");You can read from the streams using the
scanf
function,
which reads from stdin, and fscanf
function which reads from
the specified stream, for example,
double x; int items; items = scanf("%g",&x); items = fscanf(stdin,"%g",&x); items = fscanf(mystream,"%g",&x);
int main(int argc, char** argv){}where
argc
, argument count, is the number of command-line
arguments (where the name of the program is also counted), and
argv
is the array of strings of the size argc
that holds the command-line arguments (where the first element,
argv[0]
is the name of the program and argv[1]
is the first actual argument).
When the program is run the operating system calls the main
function and provides its arguments as the array of blank-separated
strings taken from the command that ran the program.
You can convert a string representation of a double number into
the very double number using the function atof
from
stdlib.h
, "ascii to double", for example,
int main(int argc, char** argv){ if(argc<2) printf("there was no argument\n"); else { double x = atof(argv[1]); printf("x = %g\n",x); } return 0; }