6.21 Files |
stdlib
I/O functions#include <stdio.h>
fopen()
fclose()
stream
and flush all data. Harbison p346.
fgets()
stream
. Harbison p356.
fputs()
stream
. Harbison p366.
fseek()
Sets file position. Kernighan p248. Harbison p352.
ftell()
Returns file position. Kernighan p248. Harbison p352.
rewind()
fgetpos()
fsetpos()
fflush()
remove()
rename()
stdlib
error functions#include <stdio.h>
#include <errno.h>
#include <string.h>
extern int errno;
This integer is set when a routine
reports an error. It is NEVER cleared by a routine.
It should only be checked after an error occurs.
strerror()
"Convert" the error number to a string.
perror()
Print the string associated with an error.
ferror()
File error. Harbison p382.
feof()
End-of-file.
clearerr()
Clear file error.
(Avoid these functions for portability)
open
close
creat
read
write
lseek
File access examples. ftp://lt.tucson.az.us/pub/c/file-or-stdin.c
/* Louis Taber, 3/18/2001 * * -- Use stdin or file name on command line. * * copy stdin to stdout if no file name is specified * * else opern file and send to stdout */ #include <stdio.h> void filecopy(FILE *, FILE *); int main(int argc, char *argv[]) { FILE *fp; if( argc == 1 ) /* No arguments -- use std input */ { filecopy(stdin, stdout); } else { if((fp = fopen( argv[1], "r")) == NULL) { printf("%s(line %d): can't open: %s\n", __FILE__, __LINE__, argv[1]); return 1; } else { filecopy(fp, stdout); fclose(fp); } } return 0; } /* filecopy: copy file ifp to file ofp */ void filecopy(FILE *ifp, FILE *ofp) { int c; while(( c= getc(ifp)) != EOF) putc(c, ofp); }
Program to read the roads for the route lab. ftp://lt.tucson.az.us/pub/c/read-roads.c
/* Louis Taber 3/18/2001 * * -- Read roads * * Example program for fscanf() * * */ #include <stdio.h> int main(void) { FILE *fp; int zip1, zip2, miles; char comment[200]; if((fp = fopen( "route.dat", "r")) == NULL) { printf("%s(line %d): can't open: route.dat\n", __FILE__, __LINE__); return 1; } else { do { if( fscanf( fp, "%d %d %d %s\n", &zip1, &zip2, &miles, comment) <0 ) break; printf("From zip %05d to zip %05d is %5d miles (%s) \n", zip1, zip2, miles, comment); } while( zip1 != 0 ); fclose(fp); } return 0; }
6.21 Files |