HP C/iX Library Reference Manual (30026-90004)
152 Chapter5
HP C/iX Library Function Descriptions
fgets
if(argc != 3) {
printf("Usage: cp fromfile tofile\n");
exit(1);
}
from = fopen(argv[1], "r");
if(from == NULL) {
printf("Can't open %s.\n", argv[1]);
exit(1);
}
to = fopen(argv[2], "w");
if(to == NULL) {
printf("Can't create %s.\n", argv[2]);
exit(1);
}
while(fgets(line, 256, from) != NULL)
fputs(line, to);
exit(0);
}
The program above accepts two arguments: the first is the name of the file to be copied,
and the second is the name of the file to be created. The first file is opened for reading, and
the second file is created for writing. The data from the first file is copied directly to the
newly created file.
In this program, the return value of fgets() is compared to NULL in the while loop,
because fgets() returns the null pointer when it reaches the end of its input. You can
easily convert this program to a file print command by doing the following:
1. Change the argc comparison to
if(argc != 2)...
2. Remove the to file pointer.
3. Remove the block of code that uses fopen() to open the new file, and assign a value to
to.
4. Change the fputs() call to
fputs(line, stdout);
The new file print program should look like this:
#include <stdio.h>
main(argc, argv)
int argc;
char *argv[ ];
{
char c, line[256], *fgets();
FILE *from;
if(argc < 2) {
printf("Usage: cat file\n");
exit(1);
}
from = fopen(argv[1], "r");
if(from == NULL) {