You are on page 1of 13

Topic X Files

LEARNING OUTCOMES
By the end of this topic, you should be able to:
1.

Write C programs which have file manipulation; and

2.

Input data from file and channel output to a file.

X INTRODUCTION
Data that is used in the programming examples in the topics before is only
temporary. After the program has ended, the data will be lost. Therefore, ways to
keep data permanently has to be known. In this topic, you will learn about files
used to store data.

4.1

FILE SUPPORT IN C PROGRAMS

C language provides many standard functions for file input output operations.
With this support, we can write C programs to read data from files. Program
data can be kept in data files that can be used repetitively. In addition, we can
write programs that channel output to files.
There are two methods of accessing data that is stored in files, which is
sequential or random access. These access methods determine how data is read,
written, modified and deleted by the program.
When a data is accessed sequentially, it will be read in the order it is written. To
read a sequential file is like playing a cassette tape; we need to play it in order to
ensure the songs are on the tape. Accessing a file randomly is like playing a CD;
you can directly access and play the songs in any order.
Files in C language are categorised into two types: binary file or text file. Binary
files can keep data in smaller sizes but text files are easier to use.

TOPIC 4

4.1.1

FILES

W 85

Binary File

Normally, it was known as a file that is not formatted, and keeps data in blocks
that has contiguous bytes. There is a special standard library file, to process
binary files. Binary files will not be discussed further in this topic or used in any
of the example.

4.1.2

Text File

Text files are sequence of characters that can be created using notepad.exe or any
other text editor that you normally use. The file extension is normally .txt or .dat.

4.2

FILE OPERATIONS

Only sequential file access will be discussed in this topic. Usually, there are three
operations that can be done to a sequential access file, which are create file,
reading and writing data and closing a file.
(a)

Creating a file  fopen();

(b)

Reading a file  fscanf();

(c)

Writing to a file  fprintf(); and

(d)

Closing a file  fclose().

4.2.1

fopen()

Before any operation can be carried out on a file, it must be opened first. In C,
when opening any file, we must send file name and access mode (either we want
to read, write or add data to a file). The relevant function used is fopen().
Format to invoke (call) it is as below:
fopen(file_name,

access_mode)

The file_name is the name of the file to be opened, whereas access_mode is the
mode used to access the file and will be explained in detail later. The fopen()
function returns a pointer that will point to the file opened. This pointer is used
later in the operations that are carried out on the file. Usually, the pointer will be
kept in a variable type FILE *. Look at the code segment:
FILE *fptr;
Fptr = fopen(datafile r);

86 X

TOPIC 4

FILES

fptr is a variable that is declared to keep the file pointer. After the calling of
fopen()function ends, the pointer pointing to the file datafile will be returned
by the function. The pointer will then be assigned to fptr.
Access mode of any file determines the operations that can be done on that file.
Table 4.1 shows the access modes that are specified in the fopen()function calls.
Table 4.1: Access Modes
Access Modes

Explanation

File is opened for read only

File is opened for writing only (start from the beginning of file)

File is opened for writing only (start from the end of file)

r+

File is opened for updating (read and write)

w+

File is opened for updating (create, read and write)

a+

File is opened for updating (read the whole file or writing at the
end of file.)

The code segment below shows the usage of fopen() function to open the file
input and file output. File input is opened for reading only whereas file output is
opened for writing only.
FILE *fptr1, *fptr2;
fptr1 = fopen(input, r);
fptr2 = fopen(output, w);
Sometimes the file that is required to be opened cannot be opened using the
fopen() function. For example, we want to open a file to be read, but the file
does not really exist. In this situation, the fopen() function will return a null
pointer (represented by the value NULL) if it fails to open the file in the required
mode.
It is important that we can trace the event so that the errors that cause the file
operation to return a null pointer can be avoided. The code segment below shows
how to trace the return of null pointer by fopen().
fptr = fopen(inputfile, r);
if (fptr == NULL) {
printf(File cannot be opened\n);
exit(1); /* end program when file fails to
}

open */

TOPIC 4

FILES

W 87

The if statement in the code segment tests whether the opening of inputfile is
successful or fails by testing if fptr is equivalent to NULL or not. If fptr is
NULL, it means that the file failed to be opened. If this happens an error message
will be displayed followed by calling of the exit()function. The exit()
function is a library function to stop execution of a program. To use it, we must
use the header file stdlib.h together with the program by entering the preprocessor command at the beginning of the program.
#include <stdlib.h>

ACTIVITY 4.1
1.

Write a code segment to open an existing file, named student.txt,


for reading and writing.

2.

What are the statements that need to be inserted into a program to


test if the file to be opened exists in the system or not?

4.2.2

fclose()

When we have finished operating on a file, the file needs to be closed. The
fclose() function is a function to close a file.
To call to the function to close a file is pointed to by a file pointer fptr as shown
below:
fclose(fptr);
The following program shows an example calling both the fopen() and
fclose() functions to open and close the file.

#include <stdio.h>
#include <stdlib.h>
void main (void)
{
FILE *fptr;
fptr = fopen(datafile, r);/*open file to read*/
if (fptr == NULL) {
printf(File datafile cannot be opened\n);
exit(1);

88 X

TOPIC 4

FILES

}
:
:
fclose(fptr);

/* file closed */

4.2.3

fprintf()

We can use the fprintf() function to print all types of data from a file. The
syntax to call the function is as follows:
int fprintf(fptr, output_format [, values_list])
Calls to the fprintf() function is nearly the same as calling the printf()
function. The difference with printf() is that it has an additional parameter; the
first parameter is a file pointer to some output file.
An example of using fprintf() function is shown in Example 4.1. This program
prints to an output file the values to the power of two for all numbers between 1
and 100.
Example 4.1: How to use fprintf() function.
/* Prints to the power of two numbers 1 - 100 to output file */
#include <stdio.h>
#include <stdlib.h>
void main(void)
{
FILE *fptr;
int x, power2;
fptr = fopen(output, w);
if (fptr == NULL)
{
printf(Cannot open output file\n);
exit(1);
}
for(x = 1; x <= 100; x++)
{
power2 = x * x; /*written to output file*/
fprintf(fptr, %d\n, power2);
}

TOPIC 4

FILES

W 89

fclose(fptr);
}
Output in the file named output:
1
4
9
16
25
36
49
64
81
100

ACTIVITY 4.2
Write a program that will input three integer numbers. Calculate the
average of these numbers. Write to a file named average.dat these
three numbers and the average. Execute your program several times,
so that the data in the average.dat file is written to every time you run
your program.

4.2.4

fscanf()

The fscanf() function can be used to read many types of data from a file. The
syntax to use the function is as follows:
fscanf(fptr, format_input [, address_list]);
We will see how the fscanf() function resembles the scanf() function; the
difference is in the fscanf() first parameter which is a file pointer to some input
file.
Example 4.2 below reads data from file data1 and displays the data on the screen.
The data that is contained in the file is the matric number as well as the grade for
a group of students.

90 X

TOPIC 4

FILES

Example 4.2: Read data from file and displays on the screen.
/* Read data from file and display it on the screen */
#include <stdio.h>
#include <stdlib.h>
void main (void)
{
FILE *fptr;
int x, total, matricno;
char gr;
fptr = fopen(data1, r);
if (fptr == NULL)
{
printf(File data1 cannot be opened\n);
exit(1);
}
fscanf(fptr, %d, &total);
Reading from
for (x = 0; x < total; x++)
data file
{
fscanf(fptr, %d %c, &matricno,&gr);
printf(Matric Number: %d\tGrade: %c\n, matricno, gr);
}
fclose(fptr);
}
After the file data1 has been successfully opened, the program will read the first
data in the file which is the total number of students. Based on the number of
students, the program will loop to read the matric number and the grade for each
student. An example of the file data1 that is appropriate to the program is given
below:
File: data1
10
1101 C
1102 E
1202 A
1203 B
1302 B
1305 C
1306 D
1401 C
1402 B
1500 C

TOPIC 4

FILES

W 91

The first line in file data1 has the total number of students, which is 10. Each line
after that has data for each student, which is the matric number, followed by the
grade. The output generated by the program for the data file is given below:
Matric
Matric
Matric
Matric
Matric
Matric
Matric
Matric
Matric
Matric

Number:
Number:
Number:
Number:
Number:
Number:
Number:
Number:
Number:
Number:

1101
1102
1202
1203
1302
1305
1306
1401
1402
1500

Grade:
Grade:
Grade:
Grade:
Grade:
Grade:
Grade:
Grade:
Grade:
Grade:

C
E
A
B
B
C
D
C
B
C

If the fscanf() function reaches the end of the file while reading, it will return
an EOF value. This value can be used as a sentinel value while reading data from
a file.

ACTIVITY 4.3
Answer the questions below based on the program segment given:
#include <stdio.h>
void main()
{
FILE *pt1, *pt2;
int a; float b; char c;
pt1 = fopen(sample.old, r);
pt2 = fopen(sample.new, w);
... // your answer starts here
fclose(pt1);
fclose(pt2);
}
1.
2.
3.

Read the values for a, b and c from the file sample.old.


Request for an input from the user.
Write the new values for a, b and c into the file sample.new.

92 X

TOPIC 4

FILES

ACTIVITY 4.4
Write a C program that will read lowercaseletter.txt file and write to a
new file uppercase.txt after changing each character in the file
lowercaseletter to capital letters.

4.2.5

getc()

The getc()function can be used to read a character from a file. The prototype of
this function is as follows:
getc(FILE *ptr);
The ptr is a pointer that the file will read. The getc()function would return the
character that was read from the file. If the function returns an EOF value, this
means the end of the file has been reached.
Program 4.1 aims to show the contents of a file to the screen. It uses the getc()
function to read the next character from the file and the putchar() function is
to display the character on the screen. This process continues until the getc()
function reaches the end of the file.

Program 4.1
/* Read a text file and display the contents on the
screen */
#include <stdio.h>
#include <stdlib.h>
void main (void) {
FILE *fptr;
char nfile[20]
char letter;
printf(File Name: );
gets(nfile);
fptr = fopen(nfile, r)
if (fptr == NULL) {
printf(File %s cannot be opened\n, nfile);
exit(1);

TOPIC 4

FILES

W 93

}
do {
letter = getc(fptr);
if (letter == EOF)
break;
putchar(letter);
} while (1);
fclose(fptr);
}

4.2.6

putc()

We can use the putc() function to print a character to a file. Below is the
prototype for this function:
putc(int aks, FILE *ptr)

aks is a character that will be the output; whereas ptr is a pointer to the output file.
Program 4.2 below uses the putc()function to copy the contents of an input file
to another output file.

Program 4.2
/* Copy contents of one input file to another output
file */
#include <stdio.h>
#include <stdlib.h>
void main (void) {
FILE *f_input, *f_output
char input_name[20];
char output_name[20];
char letter;
printf(Enter input file name: );
gets(input_name);
f_input = fopen(input_name, r);
if (f_input == NULL) {
printf(Error in opening file %s\n,
input_name);
exit(1);

94 X

TOPIC 4

FILES

}
printf(Enter output file name: );
gets(output_name);
f_output = fopen(output_name, w);
if (f_output == NULL) {
printf(Error to open file %s\n,
output_name);
exit(1);
}
printf(\nCopying File %s to file %s\n,
input_name, output_name);

while ((letter = getc(f_input)) != EOF)


putc(letter, f_output);
fclose(f_input);
fclose(f_output);
}

ACTIVITY 4.5
So far, you have learnt a few instructions in this topic. Can you state the
use of each instruction listed below?

1.
2.
3.
4.
5.
6.

Instruction
fopen()
fclose()
fprintf()
fscanf()
getc
putc

Usage

TOPIC 4

FILES

W 95

SELF-CHECK 4.1
1.

Assume that the program below is kept in a file atur1.c. Write the
output that will be produced by the program if the file that is
opened is the program file itself.
#include <stdio.h>
void main(void)
FILE *fptr;
char aks;
fptr = fopen(atur1.c, r)
if (fptr == NULL) {
printf(Error opening atur1.c\n)
exit(1);
}
while (1) {
aks = getc(fptr)
if (aks == EOF
break;
if (a <= aks
&&
aks <= z
aks = A+(aks - a);
printf(%c, aks)
}
fclose(fptr)
}

2.

Consider the program code below:


#include <stdio.h>
#include <stdlib.h>
void main(void)
FILE *fptr;
int length, height, num, i;
fptr = fopen(input, r);
if (fptr == NULL) {
printf(Numbers File cannot be opened.)
exit(1);
}
fscanf(fptr, %d, &bil);
for (i=0; i < num; i++)
display(i,num);
fclose(fptr)
}

96 X

TOPIC 4

FILES

void display(int length, int height) {


int i, j
for (i=0; i < height; i++) {
for (j=0; j < height; j++
printf(*);
printf(\n);
}
}
Write the output that will be generated if the contents of input file
is as this: 3
3. Write a program that would read every positive integer number
from a file named number and then outputs the average on the
screen.
4. Modify the program in (3) so that the average output is to a file
named output.

In this topic, you have learnt how to do file input and output in C. In
particular, we have learnt how to open and close files, read data from files as
well as writing to files.

We have seen the usage of some library functions that are relevant which are
fopen(), fclose(), fprintf(), and fscanf().

fclose()
fprintf()
fscanf()
fopen()

NULL
Pointer
Random
Sequential

You might also like