5.23 Input conversion5 Notes5.21 Structures & Linked lists5.22 Files

5.22 Files

5.22.1 stdlib I/O functions

#include <stdio.h>

5.22.2 stdlib error functions

#include <stdio.h>
#include <errno.h>
#include <string.h>

5.22.3 Unix I/O functions

(Avoid these functions for portability)

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

5.23 Input conversion5 Notes5.21 Structures & Linked lists5.22 Files