File Handling In C

File handling is the way to create files in computer's permanent memory but the question arise why do we need files. 

Let's understand this by an example, assume we are creating an application to maintain student's records for any school but where student's records will stored, we will require some permanent memory space that is a file in hard disk. These files are known as data files. 


There are some advantages of using file handling 1. User can re-use the stored data. 2. User can send data files from one system to another system. 3. Data can be stored in bulk. 

C support two types of data files 1. Text File and 2. Binary file.

Text File -  

This is a normal text file that we usually create from notepad with extension .txt
This file is readable for human, it contains textual data in form of alphabets, digits ,symbols and special characters. Internally C stores data in ASCII format.

It is simple to use and access but for security point of view it is not safe, text files are not recommended to being transmitted on network. The other disadvantage of text file is it consumes large space in memory so that if we are storing huge data then don't use text files.

Binary Files - 


This file stores a collection or sequence of bytes with extension .bin. The byte have values ranging from 0 to 255. As we know that computer itself deals in bytes so that binary files increases accessing and searching data process.

It consumes less memory and safe as well but yes it is not readable to human. C provides different methods that reads binary files and get data in readable format for user.

Steps To Follow - 


User uses file handling process to write and read data, for that we need to follow some steps ...

Writing Data Into File -

1. Create a file.
2. Open a File.
3. Write data into file.
4. Close the file.

Reading Data From File -

1. Open a File.
2. Read data from file.
3. Close the file.

Library and Methods - 

C provides <stdio.h> header file that contains all related methods for file handling.

S No.
Method
Method Purpose



1
fopen()   
Open any file
2
fprintf()    
Write a formatted data into the file
3
fputs()     
Writes unformatted data into file
4
fscanf()    
Read formatted line from file and reads till white space
5
fgets()   

Read unformatted line from the file and reads till newline
6
fwrite()
Write structure variable into file
7
fread()
Read structure variable from file
8
fputc()    
Writes single character into the file
9
fgetc()    
Read single character from file

10
fputw()    
Write an integer into the file
11
fgetw()    
Read an integer from the file
12
fclose()   
Close the file
13
fseek()    
Search specific position in the file
14
ftell()     
Tells the current position of the file

15
feof()
Move pointer to the end of the file
16
rewind()   
Move pointer to the beginning of file
17
remove()  
Deletes the file
18
fflush()    
Clean the file or buffer
You can see the use of these methods in file-handling operations, except these methods we also need to understand mode, modes tells the compiler for what operation we are going to open on file.

S No.
Mode
Purpose



1
w                           
Open text file for writing purpose  
2
r   
Open text file for reading purpose
3
a    
Open text file for append purpose    
4
w+ /r+ / a+  
Open text file for both write and read purpose
7
wb
Open binary file for writing purpose  
8
rb    
Open binary file for reading purpose  
8
ab    
Open binary file for append purpose  
9
wb+/rb+/ab+   
Open binary file for both write and read purpose

Let see some macros as well, they will help in fast process.

Macros are the pre-defined keywords in C that meaning has been already defined to the compiler. We can also create our own macros as well.

S No.
Mode
Purpose



1
SEEK_SET                         
Moves pointer position to the beginning of file
2
SEEK_CUR
Moves pointer position to the current position of file
3
SEEK_END   
Moves pointer position to the end of file

Program 1 : 
Write a program to write and read students records into text file.



#include <stdio.h>

#include <stdlib.h >


void writeStudentRecord();

void displayStudentsRecord();

void updateStudentsRecord();



//Global variables
char stud_name[20];

int roll_no;

char result[10];


// File pointer variable
FILE *filePointer;


int main() {
  
int choice;

printf("Welcome To File Handlin Process In C ...\n\n");


writeStudentRecord();

displayStudentsRecord();

updateStudentsRecord();


printf("Thanks For Using This Application");

return 0;

}

FILE *filePointer - FILE is the datatype of files and available in <stdio.h>, I have created a pointer variable for FILE, it takes the reference of file in disk. Pointer will have direct access of file's memory. Understanding Pointers In C


void writeStudentRecord() {
  

printf("Enter student name\n");

scanf("%s",stud_name);


printf("Enter student roll no.\n");

scanf("%d",&roll_no);


printf("Enter student result in grades \n");

scanf("%s",result);


//Opening file, you can specify your own path for file
filePointer = fopen("c:\\studentsRecord.txt","w");


//Null validation checking
if(filePointer == NULL) {

  printf(" File could not open");

  exit (1); //available in stdlib.h

}

else{


 // fprintf specifies the type of variable 
 
 fprintf(filePointer, "student_name = %s,",stud_name);

 fprintf(filePointer, "roll_no = %d,",roll_no);

 fprintf(filePointer, "result = %s",result);


 // fputs - writes data as it is  into file 

 fputs("\n",filePointer);


 /* 
  Note - We can write structure variable as well
  fwrite method can write structure variable into file, assuming data is structure variable.

  fwrite(&data,sizeof(data),1,filePointer);  
              
 */
  
}

fclose(filePointer);

}


NOTE: - It is recommended to open file in "a" (append) mode because in write mode it overwrites new entry over new entry. 

File can be opened anywhere in the system, you can mention the path (with \).
C provides many methods to write data into file - fprintf , fputs, fwrite ,fputc etc.
I showed three ways, you can use any one of them according your requirement.
You can use any file extension example - .txt, .dat etc.  


void displayStudentsRecord(){


//Opening file, you can specify your own path for file
filePointer = fopen("c:\\studentsRecord.txt","r");
//Null checking if(filePointer == NULL) { printf(" File could not open"); exit (1); //available in stdlib.h } else{ char temp[100]; rewind(filePointer); //moves pointer to the beginning of the file. //Run loop until file ends while(!feof(filePointer)) { /* read line and get record into any string variable 50 is the number of characters will be read.*/ fgets(temp, 50, filePointer); /* If i make any condition here ex: if temp printf("%s",temp); } // end of while } // end of else //close the file fclose(filePointer); }
NOTE: - It is recommended to use rewind method before reading data because it moves pointer to the beginning of file. 

Let's see another example where we will update the record. First read the file, search the record and then update. 

I will open file in "r+" read and write mode first read and then write process will take place.

Here I will not use a+ because it will not overwrite the searched record it will add new entry.


void updateStudentsRecord() {


filePointer = fopen("c:\\studentsRecord.txt","r+");


if(filePointer == NULL) {

  printf(" File could not open");

  exit (1); //available in stdlib.h

}

else{
 
 int rn;
 
 //moves pointer to the beginning of file
 rewind(filePointer);


 printf("Enter student roll no. to be updated \n");
 scanf("%d",&rn);
 

 while(!feof(filePointer)) {
  

  /* reading records from file and taking values in    
     variable
  */   

  fscanf(filePointer,"%s %d %s",stud_name,&roll_no,result);


  // searching record
  if (rn == roll_no){ 
    

    // Updating dummy record, you can take input from user.

    fprintf(filePointer, "student_name = %s,","test");

    fprintf(filePointer, "roll_no = %d,",3);

    fprintf(filePointer, "result = %s","test"); 

    fputs("\n",filePointer);
  
  } 

}

//Closing file
fclose(filePointer);

}

}

Program 2 : 
Write a program to write and read students records into binary file.

Program will be same, only two changes will require.
1. Change file name extension .bin
2. Use binary modes wb/rb/ab/wb+/rb+ab+

Thanks for reading, please share your comments and suggestions.

No comments

Powered by Blogger.