Module5 Chap1
Module5 Chap1
MODULE – 5
Structure, Union, and Enumerated Data Type: Introduction, structures and functions, Unions,
unions inside structures, Enumerated data type.
Files: Introduction to files, using files in C, reading and writing data files, Detecting end of file
Textbook: Chapter 15.1 – 15.10, 16.1-16.5
CHAPTER 2 FILES
2.1 INTRODUCTION TO FILES
A file is a collection of data stored on a secondary storage device like hard disk.
Till now, we had been processing data that was entered through the computer's keyboard.
But this task can become very tedious especially when there is a huge amount of data to
be processed.
A better solution, therefore, is to combine all the input data into a file and then design a C
program to read this data from the file whenever required.
The console-oriented I/O operations pose two major problems:
1. First, it becomes cumbersome and time-consuming to handle huge amount of data
through terminals.
2. Second, when doing I/O using terminal, the entire data is lost when either the program is
terminated or computer is turned off. Therefore, it becomes necessary to store data on a
permanent storage device (e.g. hard disks) and read whenever required, without
destroying the data.
In order to use files, we have to learn file input and output operations, i.e., how data is read
from or written to a file.
Although file I/O operations are almost same as terminal I/O, the only difference is that when
doing file I/O, the user must specify the name of the file from which data should be
read/written.
2.1.1 Buffer Associated with files
A buffer is nothing but a block of memory that is used for temporary storage of data that has to
be read from or written to a file.
The creation and operation the buffer is automatically handled by the operating system.
However, C provides some functions for buffer manipulation. The data resides in the buffer until
the buffer is flushed or written to a file.
There can be a number of files on the disk. In order to access a particular file, we must specify
the name of the file that has to be used. This is accomplished by using a file pointer variable that
points to a structure FILE (defined in stdio.h).
The syntax for declaring a file pointer is FILE *file_pointer_name;
FILE *fp;
Then, fp is declared as a file pointer.
2.2.2 Opening a File
A file must be opened before any operation can be performed on it. A file must first be opened
before data can be read from it or written to it. In order to open a file, the fopen() function is
used. The prototype of fopen() can be given as
FILE *file_pointer_name = fopen ("file_name", "Mode");
pointer_name can be anything of our choice.
file_name is the name of the file, which we want to open. While opening a file, we need to
specify the mode.
The second argument in fopen() is the mode. Mode conveys to C the type of processing that will
be done with the file.
Sl.N Mode Description
o
1 r Opens a text file in reading mode. Only reading possible. Does not create the
file if it does not exist.
2 w Only writing is possible. Create the file if it does not exist; otherwise, erase the
old content of the file and open a blank file.
3 a Only writing is possible. Create a file; if it does not exist, otherwise open the file
and write from the end of the file. (Does not erase the old content).
4 r+ Reading and writing are possible. Create a file if it does not exist, overwriting
existing data. Used for modifying content.
5 w+ Reading and writing are possible. Create a file if it does not exist. Erase old
content.
6 a+ Reading and writing are possible. Create a file if it does not exist. Append
content at the end of the file.
The above modes are used with text files only. If we want to work with binary files we use
rb, wb, ab, rb+, wb+ and ab+.
Example Code -
#include<stdio.h>
#include<stdlib.h>
void main()
{
FILE *fp=fopen("C:\\Users\\sonim\\Documents\\zoom\\stu.txt","r");
if(fp==NULL)
{
printf("\n The file could not be opened");
exit(1);
}
}
The fopen() function can fail to open the specified file if we attempt to open a non-existent file
for reading.
2.2.3 Closing a File Using fclose()
To close an open file, the fclose() function is used which disconnects a file pointer from a file.
After fclose() has disconnected the file pointer from the file, the pointer can be used to access a
different file or the same file but in a different mode. The fclose() function not only closes the
tile, but also flushes all the buffers that are maintained for that file. If we do not close a file after
using it, the system closes it automatically when the program exits. However, since there is a
limit on the number of files which can be opened simultaneously, we must close a file after it is
used.
Syntax – int fclose(FILE *fp);
Example – fclose(fp);
fp is the file pointer which points to the file that has to be closed. The function returns an integer
value which indicates fclose() was successful or not. A zero is returned if the function was
successful and a non-zero is returned if an error occurred.
If a file’s buffer has to be flushed without closing it then use fflush() function.
2.3 READING DATA FROM FILES
The reading from a file operation is performed using the following pre-defined file handling
methods.
1. getc()
2. getw()
3. fscanf()
4. fgets()
5. fread()
1. getc(*file_pointer ) - This function is used to read a character from specified file which
is opened in reading mode. It reads from the current position of the cursor. After reading
the character the cursor will be at next character.
#include<stdio.h>
int main()
FILE *fp;
char ch;
fp = fopen("MySample.txt","r");
ch = getc(fp);
fclose(fp);
return 0;
2. getw(*file_pointer ) - This function is used to read an integer value form the specified
file which is opened in reading mode. If the data in file is set of characters then it reads
ASCII values of those characters.
#include<stdio.h>
int main()
FILE *fp;
int i,j;
fp = fopen("MySample.txt","w");
putw(65,fp); // inserts A
putw(97,fp); // inserts a
fclose(fp);
fp = fopen("MySample.txt","r");
fclose(fp);
return 0;
#include<stdio.h>
int main()
int year;
FILE * fp;
fclose(fp);
return 0;
#include<stdio.h>
int main()
FILE *fp;
char str[20];
fgets(str,6,fp);
fclose(fp);
return 0;
#include<stdio.h>
#include<string.h>
int main()
{
FILE *fp;
char str[20];
fp = fopen ("file.txt", "r");
fread(str,sizeof(char),5,fp);
printf("str = %s", str);
fclose(fp);
return 0;
}
2.4 WRITING DATA TO FILES
The writing into a file operation is performed using the following pre-defined file handling
methods.
1. putc()
2. putw()
3. fprintf()
4. fputs()
5. fwrite()
#include<stdio.h>
int main(){
FILE *fp;
char ch;
fp = fopen("MySample.txt","w");
putc('A',fp);
ch = 'B';
putc(ch,fp);
fclose(fp);
return 0;
2. putw( int, *file_pointer ) - This function is used to writes/inserts an integer value to the
specified file when the file is opened in writing mode.
#include<stdio.h>
int main()
FILE *fp;
int i,j;
fp = fopen("MySample.txt","w");
putw(65,fp); // inserts A
putw(97,fp); // inserts a
fclose(fp);
fp = fopen("MySample.txt","r");
fclose(fp);
return 0;
#include<stdio.h>
int main()
FILE *fp;
int i = 10;
fp = fopen("MySample.txt","w");
fprintf(fp,text);
fclose(fp);
return 0;
4. fputs( "string", *file_pointer ) - TThis method is used to insert string data into specified
file which is opened in writing mode.
#include<stdio.h>
int main()
FILE *fp;
fp = fopen("MySample.txt","w");
fclose(fp);
return 0;
#include<stdio.h>
int main()
FILE *fp;
fp = fopen("MySample.txt","w");
fwrite(text,sizeof(char),5,fp);
fclose(fp);
return 0;
1. EOF
2. feof
EOF
While reading the file, character by character, the programmer can compare the character that
has been read with EOF, which is a symbolic constant defined in stdio.h.
This is demo!
This is demo!
Example
#include <stdio.h>
int main() {
int c = getc(f);
while (c != EOF) {
putchar(c);
c = getc(f);
fclose(f);
return 0;
Output
This is demo!
This is demo!
In the above program, file is opened by using fopen(). When integer variable c is not equal to
EOF, it will read the file.
feof()
We can use the standard library function feof() which is defined in stdio.h.
The function feof() takes the file pointer as an argument and returns zero (false) when the end of
file has not been reached and a one (true) if the end of file has been reached.
Example – Let’s say we have “new.txt” file with the following content.
This is demo!
This is demo!
#include <stdio.h>
#include<stdlib.h>
void main()
char str[100];
if(fp==NULL)
exit(1);
while(1)
fgets(str,79,fp);
if(feof(fp))
break;
printf("%s",str);
Output
}
This is demo!
fclose(fp); This is demo!
}
The function feof() is checking that pointer has reached to the end of file or not.