UMBC CS 201, Spring 02
UMBC CMSC 201 Spring '02 CSEE | 201 | 201 S'02 | 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: ?? ** Section: 101 ** SSN: 123-45-6789 ** EMail: chang@cs.umbc.edu ** ** 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 ; ifp = fopen("test_data.dat", "r") ; if (ifp == NULL) { printf ("Error opening test_data.dat\n"); exit (-1); } fscanf(ifp, "%lf", &x) ; fclose(ifp) ; 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 S'02 | lectures | news | help

Wednesday, 03-Apr-2002 16:40:26 EST