File example

 

#include<stdio.h>

#include<stdlib.h>         /* must use this library to use exit program */

 

/* Chapter 11 page 437 #7 */

int main()

{

 

FILE *cars;       /* declare that cars is a file */

 

int car, miles, gallons, mpg;

cars = fopen(“A:auto.txt”,”r”);    /* open cars for reading – this file is called auto.txt on the A drive */

if (cars == NULL)       /* test if the file exists */

    {

            printf(“\nFailed to open file. \n”);

            exit(1);

     }

printf(“\t Car Data ”);

printf(“\n Car \t Miles \t Gallons \t MPG”);    /* print heading for output */

while (fscanf(cars,”%2d %4d %2d”,&car,&miles,&gallons) != EOF)

/* read from file cars the car number, the miles traveled and the gallons until end of file found */

{

            mpg=miles/gallons;

            printf(“\n %2d \t %4d \t %2d \t %2d”,car,miles,gallons,mpg);

}

fclose(cars);  /*close the car file */

return 0;

}

 

Input file – entered in Notepad, saved as auto.txt

 

54025019

62052538

710123 8

85132286

97023514

 

Program Output

 

 

Return to 1336 home page