Programming in C

(Barry) #1
Special Functions for Working with Files 369

Characters stored in the array pointed to by bufferare written to the file identified by
filePtruntil the null character is reached.The terminating null character is notwritten
to the file.
There are also analogous functions called getsand putsthat can be used to read a
line from the terminal and write a line to the terminal, respectively.These functions are
described in Appendix B.


stdin,stdout, and stderr


When a C program is executed, three files are automatically opened by the system for
use by the program.These files are identified by the constantFILEpointers stdin,
stdout,and stderr, which are defined in <stdio.h>.The FILEpointer stdinidentifies
the standard input of the program and is normally associated with your terminal win-
dow. All standard I/O functions that perform input and do not take a FILEpointer as an
argument get their input from stdin.For example, the scanffunction reads its input
from stdin, and a call to this function is equivalent to a call to the fscanffunction with
stdinas the first argument. So, the call


fscanf (stdin, "%i", &i);


reads in the next integer value from the standard input, which is normally your terminal
window. If the input to your program has been redirected to a file, this call reads the
next integer value from the file to which the standard input has been redirected.
As you might have guessed,stdoutrefers to the standard output, which is normally
also associated with your terminal window. So, a call such as


printf ("hello there.\n");


can be replaced by an equivalent call to the fprintffunction with stdoutas the first
argument:


fprintf (stdout, "hello there.\n");


The FILEpointer stderridentifies the standard error file.This is where most of the
error messages produced by the system are written and is also normally associated with
your terminal window.The reason stderrexists is so that error messages can be logged
to a device or file other than where the normal output is written.This is particularly
desirable when the program’s output is redirected to a file. In such a case, the normal
output is written into the file, but any system error messages still appear in your window.
You might want to write your own error messages to stderrfor this same reason. As an
example, the fprintfcall in the following statement:


if ( (inFile = fopen ("data", "r")) == NULL )
{
fprintf (stderr, "Can't open data for reading.\n");
...
}

Free download pdf