Every programs we were doing before were using Memory for storage and all those memory would wipe out once the program is terminated.But sometime the case is different,what if we need all those data again,We need to re-enter all those bulky data again,which will again be wiped out once the program is terminated.
So we need to store the data in such a place such that it can be retrieved and displayed again and again.This is why we need files.The place about which we previously talked is the file on the disk.So we need File Handling to work with files.Let us see how a file can be handled.
Various Operations in Files
- Creating a File
- Opening a File
- Reading from a File
- Writing to a File
- Closing a File
File Opening Modes in C
Before performing any operations in files,we must create/open the file . Here are the various File opening modes in C.
- "r" : It searches the file.If the file opens up successfully,the function fopen() loads the file from disk to memory and sets a pointer pointing to the first character in the file.If the file cannot be opened fopen() returns NULL.The "r" mode is used when we need to read from a file.
- "w":It searches the file,if the file exists the content in it will be overwritten,if the file does not exists a new file will be created.fopen() returns NULL,if the file could not be opened.The "w" mode is used when we want to write a file.
- "a":It searches file,if the file exists fopen() loads the file into memory and sets a pointer that points to the last character in the file.If the file does not exists a new file will be created.If the file couldn't be opened fopen() returns NULL.The "a" mode is used when we want to add content at the end of file.
- "r+":It searches the file,if file opens up successfully, fopen() loads it into memory and sets a pointer pointing to the first character of the file. fopen() returns NULL if file cannot be opened. The "r+" mode is used to read from existing file,writing new contents and modifying contents in the file.
- "w+":It searches the file.If the file opens the contents are overwritten.If the file does not exists a new file will be created.fopen() returns NULL if file couldn't be opened.The "w+" mode is used to write new contents and reading them back.
- "a+":It searches the file.If the file opens fopen() loads it into memory and sets a pointer pointing to the first character of the file.If the file doesnot exists new file is created.If file couldn't be opened NULL is returned by fopen(). The "a+" mode is used to read existing content and appending new content to the end of file.
Opening a File
The function fopen is used to open a file.
Syntax
fopen("file_Name","opening_mode");
The fopen function performs following tasks.
- Searches the file on disk
- Loads the file from disk to the computer memory.But why should we load the file into Memory?This is because accessing each and every character of the file from disk takes lots of time and writing every time to the files in the disk is slow and difficult.so fopen loads the file from disk to memory(Buffer) and after we write to the file the content from Buffer is transferred to the disk.
- It sets a pointer pointing to the first character of the file in buffer.
File Pointer and Its Significance
To performs various operations in file, Informations like mode of opening,size of the file,place in the file from where the operations would be performed are to be known.All of such information are gathered together by fopen function in a structure called FILE. So fopen returns the address of the FILE structure .
So to store the address of the structure we need a File Pointer.
We declare the FILE pointer in the following way.
FILE *pointer_Name;
Lots of theory,now let us see a program to demonstrate file Handling
#include<stdio.h>
#include<stdlib.h>
int main()
{
FILE *ptr;
char ch;
ptr = fopen("student.txt","r");
if(ptr == NULL)
{
printf("Couldnot open the file");
exit(1);
}
while(1)
{
ch = fgetc(ptr);
if(ch == EOF)
break;
printf("%c",ch);
}
fclose(ptr);
return 0;
}
If the file student.txt exist in your current directory,it will display the contents in your screen.
Here we are trying to open the file in read-only mode ,it the file doesnot exist the function returns NULL .
Inside the while loop we are using the fgetc function. fgetc reads the character from the current pointer position ,moves the pointer to next character and returns what is read ,and that value is being stored in our ch variable.
To get out from the while loop,we need to know when the file ends.The end of file is a character with the ASCII value of 26 .When the function fgetc reads that character it returns a macro EOF which is defined under stdio.h header.
Once out of the loop we use a function fclose to close the file.
Closing a File
To close a file we use the file pointer instead of the file name.Closing the file removes the buffer associated with the file from memory.
Syntax
fclose(pointer_name);
Writing to a File
We use some library function to write to a file.Following program illustrates writing data to a file.
#include<stdio.h>
#include<stdlib.h>
struct student
{
int rollNo;
char name[20];
};
int main()
{
struct student s[5];
FILE *ptr;
ptr = fopen("student.txt","w");
if(ptr == NULL)
{
printf("Couldnot open the file");
exit(1);
}
for(int i = 0 ; i < 5 ; i++)
{
printf("Enter the name of student\n");
scanf(" %[^\n]",s[i].name);
printf("Enter the roll number\n");
scanf("%d",&s[i].rollNo);
fprintf(ptr,"%s%d",s[i].name,s[i].rollNo);
}
fclose(ptr);
return 0;
}
The output is:
Enter the name of student
Abhilekh Gautam
Enter the roll number
1
Enter the name of student
Ankit Lamichhane
Enter the roll number
2
Enter the name of student
Avyash Gautam
Enter the roll number
3
Enter the name of student
Ramesh Paudel
Enter the roll number
4
Enter the name of student
Samikshya Adhikari
Enter the roll number
5
Here in the above program we have created Array of Structure and declared variable for the structure of that type.
We are opening the file in "w" mode,which creates a new file if that file does not exists earlier and overwrites the content if it exists already.You should see a file named 'student.txt' in the computer in the directory where you are currently working.
We are using the function fprint which writes the data to a structure,the function is similar to printf function ,except the fact that a FILE pointer is included as the first parameter of the function.
We read the data into the structure variable using scanf and then dumped those input into the file in the disk.
I/O In Binary Mode
Reading and writing to a file in binary mode uses two functions fread and fwrite .
A C program to input name,address,faculty,program and GPA of 500 student and store the resut in Result.dat data file and display the record of those student whose faculty is Engineering.
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
//structure declration
struct student
{
char name[20],faculty[20];
float GPA;
};
int main()
{
struct student s[500],s1[500];
FILE *ptr;
//opens the file
ptr = fopen("RESULT.dat","w+b");
if(ptr == NULL)
{
printf("Cannot open file");
exit(1);
}
for(int i = 0 ; i < 500 ; i++)
{
printf("Enter name\n");
scanf(" %[^\n]",s[i].name);
printf("Enter faculty\n");
scanf(" %s[^\n]",s[i].faculty);
printf("Enter GPA\n");
scanf("%f",&s[i].GPA);
while(s[i].GPA > 4.0)
{
printf("GPA cannot be greater than 4.0\n");
printf("Enter GPA\n");
scanf("%f",&s[i].GPA);
}
}
fwrite(&s,sizeof(s),2,ptr);
rewind(ptr);
fread(&s1,sizeof(s1),2,ptr);
for(int i = 0 ; i < 500 ;i++)
{
if((strcmp(s1[i].faculty,"Engineering")==0 ))
printf("Name:%s\n",s1[i].name);
printf("Faculty:%s\n",s1[i].faculty,);
printf("GPA:%.2f\n",s1[i].GPA);
}
fclose(ptr);
return 0;
}
Here,the file opening mode is "w+b" the 'b' here indicates that file is being opened in binary mode.We have a structure student here,in which we are writing the data entered by user.
We are using a function fwrite here which writes to a file.
fwrite(&s,sizeof(s),2,ptr);
- Here,the first parameter is the address of structure to be written in the disk.
- The second argument is the size of the structure in bytes.
- The third argument is the number of such structure that we want to write at a time.
- The Fourth Parameter is the file Pointer.
rewind(ptr);
The rewind function set the cursor to the beginning of file.We need to do so because after writing to the file the cursor remains at the end of file, But after writing to a file we need to read a file for which we need to set the cursor at the beginning of the file.
Again then we have fread function .
fread(&s1,sizeof(s1),2,ptr);
- Here,the first parameter is the address of structure .
- The second argument is the size of the structure in bytes.
- The third argument is the number of such structure that we want to write at a time.
- The Fourth Parameter is the file Pointer.
The fread function writes to the structure s1. It's syntax is similar to that of fwrite.
Now to display the records of student form the Engineering Faculty where we used a String handling function to compare the two string and display the record accordingly.
Connect with me in Twitter @abhilekh_gautam
Best explanation😊keep it up🙂
ReplyDelete