UMBC CS 201, Fall 05
UMBC CMSC 201 Fall '05
CSEE | 201 | 201 F'05 | lectures | news | help

files and fscanf

This example shows an alternate form of scanf called fscanf. This function allows us to read input from a file instead of from the keyboard.

In order to read from a file we must first open the file using the function fopen(). fopen() takes two arguments, the name of the file to open and the mode in which to open the file. If we want to open the file to read from it, the mode we'll use is "r". If we want to write to a file, we'll open it with mode "w". There are many modes available and they are discussed in Chapter 11.

If fopen() manages to open the file sucessfully, it returns a file pointer (FILE*) which can then be used to access the contents of the file by passing it to fscanf() as shown in the example program below. If the file cannot be opened, then fopen() will return NULL. Whenever you attempt to open a file with fopen(), you'll need to check to see if the file was sucessfully opened. If the file couldn't be opened, then there is often nothing else your program can do and it's typical to print an error message and exit the program.

When we are finished using the file, we need to close it using the function fclose().

In the following example, the file contains only one number of type double.

The Program

/********************************************** ** File: fscanf1.c ** Author: Richard Chang ** Date: ?? ** Modified by: S. Evans ** Section: 01XX & 02XX ** EMail: ** ** This program demonstrates opening a file ** reading from that file using the fscanf ** function, and closing the file. ** *********************************************/ #include <stdio.h> #include <stdlib.h> int main ( ) { double x ; FILE *ifp ; /* try to open the file */ ifp = fopen("test_data.dat", "r") ; /* make sure the file was opened */ if (ifp == NULL) { /* if it wasn't we can't run the rest of */ /* the program, so tell the user and quit */ printf ("Error opening test_data.dat\n"); exit (-1); } /* read one item from the file */ fscanf(ifp, "%lf", &x) ; /* you must close the file when finished reading */ fclose(ifp) ; /* check to see what you read */ printf("x = %.2f\n", x) ; return 0; }

The Sample Run

linux1[77] % gcc -Wall -ansi fscanf1.c linux1[78] % more test_data.dat 1789.23 linux1[79] % a.out x = 1789.23 linux1[80] %

CSEE | 201 | 201 F'05 | lectures | news | help

Monday, 26-Sep-2005 11:20:30 EDT