Graphics Programs Reference
In-Depth Information
The bar code on the back of this topic represents a number. Because this
number is unique among the other books in a bookstore, the cashier can
scan the number at checkout and use it to reference information about this
book in the store's database. Similarly, a file descriptor is a number that is
used to reference open files. Four common functions that use file descriptors
are open() , close() , read() , and write() . All of these functions will return −1 if
there is an error. The open() function opens a file for reading and/or writing
and returns a file descriptor. The returned file descriptor is just an integer
value, but it is unique among open files. The file descriptor is passed as an
argument to the other functions like a pointer to the opened file. For the
close() function, the file descriptor is the only argument. The read() and
write() functions' arguments are the file descriptor, a pointer to the data to
read or write, and the number of bytes to read or write from that location.
The arguments to the open() function are a pointer to the filename to open
and a series of predefined flags that specify the access mode. These flags and
their usage will be explained in depth later, but for now let's take a look at a
simple note-taking program that uses file descriptors—simplenote.c. This
program accepts a note as a command-line argument and then adds it to the
end of the file /tmp/notes. This program uses several functions, including a
familiar looking error-checked heap memory allocation function. Other func-
tions are used to display a usage message and to handle fatal errors. The
usage() function is simply defined before main() , so it doesn't need a function
prototype.
simplenote.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <sys/stat.h>
void usage(char *prog_name, char *filename) {
printf("Usage: %s <data to add to %s>\n", prog_name, filename);
exit(0);
}
void fatal(char *); // A function for fatal errors
void *ec_malloc(unsigned int); // An error-checked malloc() wrapper
int main(int argc, char *argv[]) {
int fd; // file descriptor
char *buffer, *datafile;
buffer = (char *) ec_malloc(100);
datafile = (char *) ec_malloc(20);
strcpy(datafile, "/tmp/notes");
if(argc < 2) // If there aren't command-line arguments,
usage(argv[0], datafile); // display usage message and exit.
Search WWH ::




Custom Search