File Handling in C Language

File Handling in C Language

A file represents a sequence of bytes on the disk where a group of related data is stored. File is created for permanent storage of data. It is a ready-made structure.

In C language, we use a structure pointer of file type to declare a file.
FILE *fp;

C provides a number of functions that helps to perform basic file operations. Following are the functions,

Function         description
fopen()                        create a new file or open a existing file
fclose()            closes a file
getc()               reads a character from a file
putc()               writes a character to a file
fscanf()            reads a set of data from a file
fprintf()           writes a set of data to a file
getw()              reads a integer from a file
putw()             writes a integer to a file
fseek()             set the position to desire point
ftell()               gives current position in the file
rewind()          set the position to the begining point

Opening a File or Creating a File

The fopen() function is used to create a new file or to open an existing file.

General Syntax :

*fp = FILE *fopen(const char *filename, const char *mode);

Here filename is the name of the file to be opened and mode specifies the purpose of opening the file. Mode can be of following types,

*fp is the FILE pointer (FILE *fp), which will hold the reference to the opened(or created) file.

mode   description
r           opens a text file in reading mode
w         opens or create a text file in writing mode.
a          opens a text file in append mode
r+         opens a text file in both reading and writing mode
w+       opens a text file in both reading and writing mode
a+        opens a text file in both reading and writing mode
rb         opens a binary file in reading mode
wb       opens or create a binary file in writing mode
ab        opens a binary file in append mode
rb+       opens a binary file in both reading and writing mode
wb+     opens a binary file in both reading and writing mode
ab+      opens a binary file in both reading and writing mode

Closing a File

The fclose() function is used to close an already opened file.

General Syntax :
int fclose( FILE *fp );

Here fclose() function closes the file and returns zero on success, or EOF if there is an error in closing the file. This EOF is a constant defined in the header file stdio.h.

Input/Output operation on File

In the above table we have discussed about various file I/O functions to perform reading and writing on file. getc() and putc() are simplest functions used to read and write individual characters to a file.

#include<stdio.h>
#include<conio.h>
main()
{
 FILE *fp;
charch;
fp = fopen("one.txt", "w");
printf("Enter data");
while( (ch = getchar()) != EOF) {
putc(ch,fp);
 }
fclose(fp);
fp = fopen("one.txt", "r");

while( (ch = getc(fp)! = EOF)
printf("%c",ch);

fclose(fp);
}

Reading and Writing from File using fprintf() and fscanf()

#include<stdio.h>
#include<conio.h>
structemp
{
char name[10];
int age;
};

void main()
{
structemp e;
   FILE *p,*q;
   p = fopen("one.txt", "a");
   q = fopen("one.txt", "r");
printf("Enter Name and Age");
scanf("%s %d", e.name, &e.age);
fprintf(p,"%s %d", e.name, e.age);
fclose(p);
do
   {
fscanf(q,"%s %d", e.name, e.age);
printf("%s %d", e.name, e.age);
   }
while( !feof(q) );
getch();
}
In this program, we have create two FILE pointers and both are refering to the same file but in different modes. fprintf() function directly writes into the file, while fscanf() reads from the file, which can then be printed on console usinf standard printf() function.

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.

Reading and Writing in a Binary File

A Binary file is similar to the text file, but it contains only large numerical data. The Opening modes are mentioned in the table for opening modes above.

fread() and fwrite() functions are used to read and write is a binary file.

fwrite(data-element-to-be-written, size_of_elements,
                                    number_of_elements, pointer-to-file);
fread() is also used in the same way, with the same arguments like fwrite() function. Below mentioned is a simple example of writing into a binary file

const char *mytext = "The quick brown fox jumps over the lazy dog";  

FILE *bfp= fopen("test.txt", "wb");  
if (bfp) {    
fwrite(mytext, sizeof(char), strlen(mytext), bfp) ;    
fclose(bfp) ;  
}

fseek(), ftell() and rewind() functions

·         fseek() - It is used to move the reading control to different positions using fseek function.
·         ftell() - It tells the byte location of current position of cursor in file pointer.
·         rewind() - It moves the control to beginning of the file.

Program to Create a File & Write Data in it

In this program we will be creating a new file and will then store information in it.

#include<stdio.h>
#include<conio.h>

void main()
{
    FILE *fptr;
char name[20];
int age;
float salary;

/*  open for writing */
fptr = fopen("emp.txt", "w");

if (fptr == NULL)
    {
printf("File does not exists \n");
return;
    }
printf("Enter the name \n");
scanf("%s", name);
fprintf(fptr, "Name  = %s\n", name);

printf("Enter the age\n");
scanf("%d", &age);
fprintf(fptr, "Age  = %d\n", age);

printf("Enter the salary\n");
scanf("%f", &salary);
fprintf(fptr, "Salary  = %.2f\n", salary);

fclose(fptr);
}

You can add any information in the file, like we have added Name, Age and Salary for some employees, you can change the program as per your requirements.

Program to Find Size of a File

We will be using fseek() and ftell() functions to find the size of the file. There are others ways to find the file size, like looping on the whole content of file and finding out the size, but using File Handling functions makes it easier.

#include<stdio.h>
#include<conio.h>

void main()
{
    FILE *fp;
charch;
int size = 0;

fp = fopen("MyFile.txt", "r");
if (fp == NULL)
    {
printf("\nFile unable to open ");
    }
else
    {
printf("\nFile opened ");
    }
fseek(fp, 0, 2);    /* file pointer at the end of file */
size = ftell(fp);   /* take a position of file pointer in size variable */
printf("The size of given file is : %d\n", size);   
fclose(fp);
}

Program to Copy Content of One File into Another File

We already know how to open a file, read contents of a file and write into a file. So in this program, we will read from one file and simultaneously write into the other file, till we reach end of first file.

#include<stdio.h>

void main()
{  
/*
    File_1.txt is the file with content and,
    File_2.txt is the file in which content of File_1
will be copied.
    */
    FILE *fp1, *fp2;
charch;
intpos;

if ((fp1 = fopen("File_1.txt","r")) == NULL)   
    {   
printf("\nFile cannot be opened");
return;
    }
else
    {
printf("\nFile opened for copy...\n ");   
    }
fp2 = fopen("File_2.txt", "w"); 
fseek(fp1, 0L, SEEK_END); // file pointer at end of file
pos = ftell(fp1);
fseek(fp1, 0L, SEEK_SET); // file pointer set at start
while (pos--)
    {
ch = fgetc(fp1);  // copying file character by character
fputc(ch, fp2);
    }   
fcloseall();   
}

Program to Reverse the Contents of a File and Print it

#include<stdio.h>
#include<errno.h>

// to count the total number of characters inside the source file
longcount_characters(FILE *);

void main()
{
int i;
longcnt;
charch, ch1;
    FILE *fp1, *fp2;

if (fp1 = fopen("File_1.txt", "r"))   
    {
printf("The FILE has been opened...\n");
        fp2 = fopen("File_2.txt", "w");
cnt = count_characters(fp1);

/*
makes the pointer fp1 to point at the
last character of the file
        */
fseek(fp1, -1L, 2);    
printf("Number of characters to be copied %d\n", ftell(fp1));

while (cnt)
        {
ch = fgetc(fp1);
fputc(ch, fp2);
fseek(fp1, -2L, 1);   // shifts the pointer to the previous character
cnt--;
        }
printf("\n**File copied successfully in reverse order**\n");
    }
else
    {
perror("Error occured\n");
    }
fclose(fp1);
fclose(fp2);
}

/*
count the total number of characters in the file
that *f points to
*/
longcount_characters(FILE *f)
{
fseek(f, -1L, 2);
longlast_pos = ftell(f);   //returns the position of the last element of the file
last_pos++;
returnlast_pos;

}

Comments

Popular posts from this blog

પટેલ સમાજનો ઈતિહાસ જાણો : કોણ અને ક્યાંથી આવ્યા હતા પાટીદારો

Python HTML Generator using Yattag Part 1

Java Event Delegation Model, Listener and Adapter Classes