Session Twelve
Session Twelve
12.1. Introduction
A file is a place on the disk where a group of related data is stored. C supports a number of functions that
have the ability to perform basic file operations, which includes;
• Naming a file
• Opening a file
• Reading data from a file
• Writing data to a file
• Closing a file
There are two distinct ways to perform file operations in C
1. Low-level I/O and used the Unix system calls
2. High-level I/O operation and uses functions in C‟s standard I/O library
3. High Level I/O functions in C
Function Operation
fopen() Creates a new file for use / opens an existing file for use
fclose() Closes a file that had been opened for use
getc() Reads a character from a file
putc() Writes a character to file
fprintf() Writes a set of data values to a file
fscanf() Reads a set of data values from a file
getw() Reads an integer from a file
putw() Writes an integer in a file
fseek() Set the position to a desired point in a file
ftell() Fives the current position in the file(in terms of bytes from the start)
rewind() Sets the position to the beginning of the file
There are many other functions and not all are supported by all the C compilers
• Data structure: Data structure of a file is defined a FILE in the library of standard I/O function
definitions. Therefore all files should be declared as type FILE before they are used. FILE is a defined
data type
• Purpose. When we open a file we must specify what we want to do with the file, example read from or
write to it.
FILE *fp declares the variable fp as a “pointer to the data type FILE. FILE is a structure that is defined
in the I/O library.
fp = fopen(„filename, “mode”); open the file named and assigns an identifier to the FILE type pointer
fp.
The fp pointer which contains all the information about the file is subsequently used as a
communication link between the system and the program.
The statement also specifies the purpose of opening the file. Options includes;
• r = open a file for reading only
• w – opens a file for writing only.
• a – opens a file for appending (or adding) data to it.
fclose(file_pointer);
example FILE *p1,
*p2;
p1 =
fopen(“INPUT”, “w”);
p2 =
fopen(“OUTPUT”, “r”);
………
…….
fclose(p1);
fclose(p2);
Once a file is closed its file pointer can be used for another file.
Prgram Example 12.1: Program to read data keyed in through the keyboard and write it into a file,
then read the data from the file and display it on the screen
• The End-Of-File (EOF) marker is achieved through pressing <control-z>
Data to enter: This is a program to test the file handling features of C program.
#include
<stdio.h>
#include<conio.h
>
main( )
{
FILE *f1; char c;
printf("Data
Input\n\n");
/* open the INPUT file for writing */
f1 = fopen("INPUT", "w");
/* get character from the Keyboard */
while ((c=getchar()) != EOF)
putc(c, f1);
/* close the INPUT file */
fclose(f1);
printf("\nData Output \n\n");
getch();
}
Testing for End-Of-File (EOF) condition is important, as attempting to read past the EOF might either cause
the program to terminate with an error or result in an infinite loop situation.
Program Example 12.2: Write a program to read integers from a file called DATA and write all odd
integers into a file called ODD and all even integers into a file called EVEN. Test data
111 222 333 000 121
444 555 666 232 343
777 888 999 454 -1
#include <stdio.h>
#include<conio.h>
main()
{
FILE *f1, *f2, *f3;
int number, i;
fclose(f1);
f1 = fopen("DATA",
"r");
f2 = fopen("ODD",
"w");
f3 = fopen("EVEN",
"r");
fclose(f1);
fclose(f2);
fclose(f3);
f2 = fopen("ODD", "r");
f3 = fopen ("EVEN", "r");
fclose(f2);
fclose(f3);
getch();
}
fscanf Format
fscanf(fp, control string”, list);
example
fscanf(f1, “%s %d”, item, &quantity);
Program Example 12.3: Write a program to open a file named INVENTORY and store in it the
following data;
#include
<stdio.h>
#include<conio.h
>
main( )
{
FILE *fp; int number,
quantity, i;
float price, value;
char item[10],
filename[10];
fclose(fp);
fprintf(stdout, "\n\n");
fp = fopen(filename, "r");
printf("Item name Number Price Quantity Value\n");
for (i =1 ; i <=3; i++)
{
fscanf(fp, "%s %d %f %d", item, &number, &price, &quantity);
value = price * quantity;
fprintf(stdout, "%-8s %7d %8.2f %8d %11.2f\n" , item,
number, price, quantity, value);
}
fclose(fp);
getch();
}
C has two status-inquiry library functions; feof and ferror that helps to detect I/O errors in files.
feof is used to detect end-of-file condition. It take the file pointer as its only argument and returns a nonzero
integer value if all of the data from the specified file has been read and returns zero otherwise..
example if fp is a file pointer that has been opened then the statement
; if(feof(fp)) printf(“End ofdata”);
would display “End of data” on reaching the end of file condition.
Ferror function reports the status of the file indicated. It also takes the file pointer as its only argument and
returns a nonzero integer value if an error has been detected up to that point, during processing. It returns
zero otherwise. Example if (ferror(fp) != 0)
printf (“An error has occurred. \n”);
#include
<stdio.h>
#include<conio.h
>
main( )
{
char *filename;
FILE *fp1, *fp2;
int i, number;
fp1 = fopen("TEST",
"w");
for (i = 10; i<= 100;
i+=10) putw(i, fp1);
fclose(fp1);
printf("\nInput file name\n");
open_file:
scanf("%s", filename);
if((fp2 = fopen(filename, "r"))== NULL)
{
printf("Cannot open the file.\n");
printf("Type file name again.\n\n");
goto open_file;
}
else
for (i = 1;
i<= 20;
i++)
{ number =
getw(fp2);
if (feof(fp2))
{
printf("\nRan out of data.\n");
break;
}
else
printf("%d\n", number);
}
fclose(fp2);
getch();
}