5.21 Files
- When to use files
- Content of files
- Array sizes and memory costs
- Access times - Sequential and random
- File buffering
- Files in memory
#include <stdio.h>
#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;
}
Instructor: ltaber@pima.edu ** My new Home at GeoApps in Tucson ** The Pima College Site