Professional Documents
Culture Documents
Chapter 10
Chapter 10
Introduction
A collection of data which is stored on a secondary device like a hard disk is called as a file. A
file is generally used as real-life applications that contain a large amount of data. Therefore, the
file is a place on the disk where a group of related data is stored.
The programs that we executed so far accepts the input data from the keyboard at the time of
execution and writes output to the video display unit. This type of I/O is called console I/O. For
those operations, we have been using printf(), scanf(), getch(), getche(), getchar(), gets(), puts()
etc functions. Console I/O works fine as long as the amount of data in small. But in many reallife
problems involve a large volume of data, there are 2 problems.
It is time-consuming and unmanageable for handling such huge amount of data.
When the I/O terminal is used the entire data is lost if the program is terminated or the
computer is being turned off. So it is a compulsion for storing the data on a permanent
device.
Why files are needed?
When a program is terminated, the entire data is lost. Storing in a file will preserve your
data even if the program terminates.
If you have to enter a large number of data it will take a lot of time to enter them all.
However, if you have a file containing all the data, you can easily access the contents of
the file using few commands in C.
You can easily move your data from one computer to another without any changes.
1. Text files : A text file is a human readable sequence of characters and the words they form
that can be encoded into computer-readable formats such as ASCII. A text contains only textual
characters with no special formatting such as underlining or displaying characters in bold faces
or different fonts. There is no graphical information, sound or video files. A text file known as an
ASCII file and can be read by any word processor. Text files store information in consecutive
characters. These characters can be interpreted as individual data items or as a component of
strings or numbers. Text files are the normal .txt files that you can easily create using Notepad or
any simple text editors. When you open file, you will see all contents within file as plain text.
2. Binary files : Binary files are mostly the .bin files in your computer. Instead of storing data in
plain text, they store it in the binary form (0's and 1's). They can hold higher amount of data are
not readable easily and provides a better security than text files.
In contrast to ASCII files, which contains only characters (plain text), binary files contain
additional code information i.e., machine readable form. Binary files organize data into blocks
containing contagious bytes of information. These blocks represent more complex data
structures. Example : arrays and structures. A good example of binary file is the executed C
program files. Example : first.exe is a binary file.
To check given file is text or binary, open file in Turbo C/C++, if we can read file then it is text
otherwise binary. Other examples of binary files are sound, graphics, image file etc.
File Operations
In C, you can perform four major operations on the file, either text or binary:
1. Creating a new file
2. Opening an existing file
3. Closing a file
4. Reading from and writing information to a file
5. Moving to a specific location in a file.
File
Meaning of Mode During Inexistence of file
Mode
r Open for reading. If the file does not exist, fopen() returns NULL.
rb Open for reading in binary mode. If the file does not exist, fopen() returns NULL.
If the file exists, its contents are overwritten. If
w Open for writing.
the file does not exist, it will be created.
If the file exists, its contents are overwritten. If
wb Open for writing in binary mode.
the file does not exist, it will be created.
Open for append. i.e, Data is added
a If the file does not exists, it will be created.
to end of file.
Open for append in binary mode. i.e,
ab If the file does not exists, it will be created.
Data is added to end of file.
r+ Open for both reading and writing. If the file does not exist, fopen() returns NULL.
Open for both reading and writing in
rb+ If the file does not exist, fopen() returns NULL.
binary mode.
If the file exists, its contents are overwritten. If
w+ Open for both reading and writing.
the file does not exist, it will be created.
Open for both reading and writing in If the file exists, its contents are overwritten. If
wb+
binary mode. the file does not exist, it will be created.
Open for both reading and
a+ If the file does not exists, it will be created.
appending.
Open for both reading and
ab+ If the file does not exists, it will be created.
appending in binary mode.
Before reading data(info.) from an existing file we need to open in read mode. That is, fopen()
performs following task. When we open the file in "r" mode.
Firstly, it searches on the disk to the specified path to open the files.
If it finds the file, it loads the file from the disk into the buffer and it sets up file pointer that
points the first character of the pointer.
Buffer : A section of RAM reserved for temporary storage of data waiting to be directed to a
device.
Reading and writing to a text file
For reading and writing to a text file, we use the functions fprintf() and fscanf(). They are just the
file versions of printf() and scanf(). The only difference is that, fprint and fscanf expects a
pointer to the structure FILE.
Example 1: Write to a text file using fprintf()
#include <stdio.h>
#include <stdlib.h>
int main()
{
int num;
FILE *fptr;
fptr = fopen("C:\\program.txt","w");
if(fptr == NULL)
{
printf("Error!");
exit(1);
}
printf("Enter num: ");
scanf("%d",&num);
fprintf(fptr,"%d",num);
fclose(fptr);
return 0;
}
This program takes a number from user and stores in the file program.txt.
After you compile and run this program, you can see a text file program.txt created in C drive of
your computer. When you open the file, you can see the integer you entered.
Whence Meaning
SEEK_CUR Starts the offset from the current location of the cursor in the file.
Example 5: fseek()
#include <stdio.h>
#include <stdlib.h>
struct threeNum
{
int n1, n2, n3;
};
int main()
{
int n;
struct threeNum num;
FILE *fptr;
if ((fptr = fopen("C:\\program.bin","rb")) == NULL){
printf("Error! opening file");
// Program exits if the file pointer returns NULL.
exit(1);
}
// Moves the cursor to the end of the file
fseek(fptr, -sizeof(struct threeNum), SEEK_END);
for(n = 1; n < 5; ++n)
{
fread(&num, sizeof(struct threeNum), 1, fptr);
printf("n1: %d\tn2: %d\tn3: %d\n", num.n1, num.n2, num.n3);
fseek(fptr, -2*sizeof(struct threeNum), SEEK_CUR);
}
fclose(fptr);
return 0;
}
This program will start reading the records from the file program.bin in the reverse order (last to
first) and prints it.
1. Write a C program to read name and marks of n number of students from user and
store them in a file.
#include <stdio.h>
int main()
{
char name[50];
int marks, i, num;
printf("Enter number of students: ");
scanf("%d", &num);
FILE *fptr;
fptr = (fopen("C:\\student.txt", "w"));
if(fptr == NULL)
{
printf("Error!");
exit(1);
}
for(i = 0; i < num; ++i)
{
printf("For student%d\nEnter name: ", i+1);
scanf("%s", name);
printf("Enter marks: ");
scanf("%d", &marks);
fprintf(fptr,"\nName: %s \nMarks=%d \n", name, marks);
}
fclose(fptr);
return 0;
}
2. Write a C program to read name and marks of n number of students from user and
store them in a file. If the file previously exits, add the information of n students.
#include <stdio.h>
int main()
{
char name[50];
int marks, i, num;
printf("Enter number of students: ");
scanf("%d", &num);
FILE *fptr;
fptr = (fopen("C:\\student.txt", "a"));
if(fptr == NULL)
{
printf("Error!");
exit(1);
}
for(i = 0; i < num; ++i)
{
printf("For student%d\nEnter name: ", i+1);
scanf("%s", name);
printf("Enter marks: ");
scanf("%d", &marks);
fprintf(fptr,"\nName: %s \nMarks=%d \n", name, marks);
}
fclose(fptr);
return 0;
}
3. Write a C program to write all the members of an array of structures to a file using
fwrite(). Read the array from the file and display on the screen.
#include <stdio.h>
struct student
{
char name[50];
int height;
};
int main(){
struct student stud1[5], stud2[5];
FILE *fptr;
int i;
fptr = fopen("file.txt","wb");
for(i = 0; i < 5; ++i)
{
fflush(stdin);
printf("Enter name: ");
gets(stud1[i].name);
printf("Enter height: ");
scanf("%d", &stud1[i].height);
}
fwrite(stud1, sizeof(stud1), 1, fptr);
fclose(fptr);
fptr = fopen("file.txt", "rb");
fread(stud2, sizeof(stud2), 1, fptr);
for(i = 0; i < 5; ++i)
{
printf("Name: %s\nHeight: %d", stud2[i].name, stud2[i].height);
}
fclose(fptr);
}
Difference between Append and Write Mode
Write (w) mode and Append (a) mode, while opening a file are almost the same. Both are used to
write in a file. In both the modes, new file is created if it doesn't exists already.
The only difference they have is, when you open a file in the write mode, the file is reset,
resulting in deletion of any data already present in the file. While in append mode this will not
happen. Append mode is used to append or add data to the existing data of file(if any). Hence,
when you open a file in Append(a) mode, the cursor is positioned at the end of the present data in
the file.
Error Handling in C
C language does not provide any direct support for error handling. However a few methods and
variables defined in error.h header file can be used to point out error using the return statement in
a function. In C language, a function returns -1 or NULL value in case of any error and a global
variable errno is set with the error code. So the return value can be used to check error while
programming.
What is errno?
Whenever a function call is made in C language, a variable named errno is associated with it. It
is a global variable, which can be used to identify which type of error was encountered while
function execution, based on its value. Below we have the list of Error numbers and what does
they mean.
errno value Error
3 No such process
5 I/O error
10 No child processes
11 Try again
12 Out of memory
13 Permission denied
C language uses the following functions to represent error messages associated with errno:
perror(): returns the string passed to it along with the textual represention of the current errno
value.
strerror() is defined in string.h library. This method returns a pointer to the string representation
of the current errno value.
Time for an Example
#include <stdio.h>
#include <errno.h>
#include <string.h>
int main ()
{
FILE *fp;
/*
If a file, which does not exists, is opened,
we will get an error
*/
fp = fopen("IWillReturnError.txt", "r");
printf("Value of errno: %d\n ", errno);
printf("The error message is : %s\n", strerror(errno));
perror("Message from perror");
return 0;
}
Value of errno: 2
The error message is: No such file or directory
Message from perror: No such file or directory
1. Opening a file
fopen() function is used for opening a file.
Syntax:
FILE pointer_name = fopen ("file_name", "Mode");
pointer_name can be anything of your choice.
file_name is the name of the file, which you want to open. Specify the full path here like
“C:\\myfiles\\newfile.txt”.
While opening a file, you need to specify the mode. The mode that we use to read a file is “r”
which is “read only mode”.
for example:
FILE *fp;
fp = fopen("C:\\myfiles\\newfile.txt", "r");
The address of the first character is stored in pointer fp.
How to check whether the file has opened successfully?
If file does not open successfully then the pointer will be assigned a NULL value, so you can
write the logic like this:
This code will check whether the file has opened successfully or not. If the file does not open,
this will display an error message to the user.
..
FILE fpr;
fpr = fopen("C:\\myfiles\\newfile.txt", "r");
if (fpr == NULL)
{
puts("Error while opening file");
exit();
}
2. Reading a File
To read the file, we must open it first using any of the mode, for example if you only want to
read the file then open it in “r” mode. Based on the mode selected during file opening, we are
allowed to perform certain operations on the file.
C Program to read a file
fgetc( ): This function reads the character from current pointer’s position and upon successful
read moves the pointer to next character in the file. Once the pointers reaches to the end of the
file, this function returns EOF (End of File). We have used EOF in our program to determine the
end of the file.
#include <stdio.h>
int main()
{
/* Pointer to the file */
FILE *fp1;
/* Character variable to read the content of file */
char c;
if(fpw == NULL)
{
printf("Error");
exit(1);
}
return 0;
}
4. Closing a file
fclose(fp);
The fclose( ) function is used for closing an opened file. As an argument you must provide a
pointer to the file that you want to close.
An example to show Open, read, write and close operation in C
#include <stdio.h>
int main()
{
char ch;
return 0;
}
Q. WAP to read the information of a file named "data.txt" and write its contents to
another file "record.txt".
#include <stdio.h>
#include <stdlib.h> // For exit()
#include<conio.h>
int main()
{
FILE *fptr1, *fptr2;
char filename[100], c;
printf("Enter the filename to open for reading \n");
scanf("%s", filename);
// Open one file for reading
fptr1 = fopen(filename, "w+");
if (fptr1 == NULL)
{
printf("Cannot open file %s \n", filename);
exit(0);
}
printf("Enter the filename to open for writing \n");
scanf("%s", filename);
// Open another file for writing
fptr2 = fopen(filename, "w");
if (fptr2 == NULL)
{
printf("Cannot open file %s \n", filename);
exit(0);
}
// Read contents from file
c = fgetc(fptr1);
while (c != EOF)
{
fputc(c, fptr2);
c = fgetc(fptr1);
}
printf("\nContents copied to %s", filename);
fclose(fptr1);
fclose(fptr2);
getch();
return 0;
}
Q. List different types of standard I/O used in C. WAP to write name, roll no and age of five students into a
disk file name "STUDENT.DAT".
#include <stdio.h>
#include<conio.h>
struct STUDENT
{
char name[20];
int rollno;
int age;
};
int main( )
{
struct STUDENT std[5];
int i;
FILE *fp;
fp = fopen("STUDENT.dat", "w");
for(i=0; i<5; i++)
{
printf("Name: ");
scanf("%s",std[i].name);
printf( "Roll: ");
scanf("%d", &std[i].rollno);
printf("Age: ");
scanf("%d", &std[i].age);
fprintf(fp,"Name : %d\tRoll : %d\tAge : %d\n",std[i].name, std[i].rollno, std[i].age);
}
fclose(fp);
getch();
return 0;
}
Q. WAP to continuously read name, age and salary of a worker and write it into a file until user confirms to
end. Then read n from user and display the nth record in the file. Details of worker must be represented by a
structure.
#include <stdio.h>
#include<conio.h>
struct WORKER
{
char name[20];
int age;
float salary;
};
int main( )
{
struct WORKER emp;
char next[3],line[200];
int n, i=1;
FILE *fp;
fp = fopen("WORKER.txt", "w");
do
{
printf("Name: ");
scanf("%s",emp.name);
printf( "Age: ");
scanf("%d", &emp.age);
printf("Salary: ");
scanf("%f", &emp.salary);
fprintf(fp,"Name : %s\tAge : %d\tSalary : %f\n",emp.name, emp.age, emp.salary);
printf("If you don't want to enter more data , please confirm 'yes': ");
scanf("%s", next);
}while(strcmp(next, "yes")!=0);
fclose(fp);
fp=fopen("WORKER.txt","r");
printf("Enter record number you want to display : ");
scanf("%d", &n);
while (fgets(line, sizeof(line), fp))
{
if(i == n )
{
printf("%s", line);
}
i++;
}
fclose(fp);
getch();
return 0;
}
Q. WAP to store employee details in a text file. Read data from the text file, sort them in ascending order of
salary and store the sorted record to a binary file. Display the details and rank of employee given by the user.
#include <stdio.h>
#include<conio.h>
struct WORKER
{
char name[20];
int age;
float salary;
};
int main( )
{
struct WORKER emp;
char next[3],line[200];
int n, i=1;
FILE *fp;
fp = fopen("WORKER.txt", "w");
do
{
printf("Name: ");
scanf("%s",emp.name);
printf( "Age: ");
scanf("%d", &emp.age);
printf("Salary: ");
scanf("%f", &emp.salary);
fprintf(fp,"Name : %s\tAge : %d\tSalary : %f\n",emp.name, emp.age, emp.salary);
printf("If you don't want to enter more data , please confirm 'yes': ");
scanf("%s", next);
}while(strcmp(next, "yes")!=0);
fclose(fp);
fp=fopen("WORKER.txt","r");
printf("Enter record number you want to display : ");
scanf("%d", &n);
while (fgets(line, sizeof(line), fp))
{
if(i == n )
{
printf("%s", line);
}
i++;
}
fclose(fp);
getch();
return 0;
}
Q. Write a C program to read numbers from a file and write even, odd and prime numbers in separate files.
#include <stdio.h>
int main() {
FILE *fp1, *fp2, *fp3, *fp4;
int n, i, num, flag = 0;
/* open data.txt in read mode */
fp1 = fopen("data.txt", "w");
printf("Enter the value for n:");
scanf("%d", &n);
for (i = 0; i <= n; i++)
fprintf(fp1, "%d ", i);
fprintf(fp1, "\n");
fclose(fp1);
/* open files to write even, odd and prime nos separately */
fp1 = fopen("data.txt", "r");
fp2 = fopen("even.txt", "w");
fp3 = fopen("odd.txt", "w");
fp4 = fopen("prime.txt", "w");
fprintf(fp2, "Even Numbers:\n");
fprintf(fp3, "Odd Numbers:\n");
fprintf(fp4, "Prime Numbers:\n");
/* print even, odd and prime numbers in separate files */
while (!feof(fp1)) {
fscanf(fp1, "%d", &num);
if (num % 2 == 0) {
fprintf(fp2, "%d ", num);
} else {
if (num > 1) {
for (i = 2; i < num; i++) {
if (num % i == 0) {
flag = 1;
break;
}
}
if (!flag) {
fprintf(fp4, "%d ", num);
}
}
fprintf(fp3, "%d ", num);
flag = 0;
}
}
/* close all opened files */
fclose(fp1);
fclose(fp2);
fclose(fp3);
fclose(fp4);
return 0;
}