Page 125 - Programming Microcontrollers in C
P. 125
110 Chapter 2 Advanced C Topics
Input and Output
C has no provision for either input or output within the language.
Any such operations must be programmed as functions that are called
from the programs. There are several standard I/O functions that are
always included with a complete C compiler. However, in many in
stances, compilers for very small microcontrollers will have no built-in
input/output capability.
File accesses are through a set of functions and a special struc
ture. The struct FILE is a structure that contains all parameters
needed to access a file. The file pointer is given a value by
FILE *fp;
FILE *fopen(char* name, char* mode);
Here name is a pointer to a character array that contains the name
of the file. This name can be simply the file name if the file resides in
the default directory, or it can be the complete path name-file name
combination for files elsewhere in the file system. The string pointed
to by mode is a one or two character string. The various modes are
“r” read only
“w” write only
“a” append
and sometimes
“b” binary
“rw” read/write
To open a file, the program must contain a statement
fp=fopen(name,mode);
where fp is declared as a pointer to the type FILE. Once the file is
opened, all file accesses will use fp as an argument in some way.
There are two single character file access functions:
int getc(FILE* fp);
int putc(int c, FILE* fp);
The first function returns a character from an open file fp and the
second puts a character c onto an open file fp. There are three special
file pointers created by the operating system when a program is loaded.
These three file pointers are stdin, stdout, and stderr. stdin