You are on page 1of 15

File Handling in C

1. Introduction
So far the operations using the C program are done on a prompt/terminal which is
not stored anywhere. But in the software industry, most programs are written to
store the information fetched from the program. One such way is to store the
fetched information in a file.
_
2. What is File?

“File is a collection of data that stored on secondary memory like hard disk of a
computer”.

3. Why do we need file handling in C?

The output of a C program is generally deleted when the program is closed.


Sometimes, we need to store that output for purposes like data analysis, result
presentation, comparison of output for different conditions, etc. The use of file
handling is exactly what the situation calls for.
In order to understand why file handling makes programming easier, let us look at a
few reasons:

 Reusability: The file-handling process keeps track of the information created after
the program has been run.
 Portability: Without losing any data files can be transferred to another in the
computer system. The risk of flawed coding is minimized with this feature.
 Efficient: A large amount of input may be required for some programs. File
handling allows you to easily access a part of a code using individual commands
which saves a lot of time and reduces the chance of errors.
 Storage Capacity: Files allow you to store data without having to worry about
storing everything simultaneously in a program.

4. Types of Files in C
C programming language supports two types of files and they are as follows...

 Text Files
 Binary Files

Text Files: Text files contain data in the form of ASCII characters and are generally
used to store a stream of characters. Each line in a text file ends with a new line
character (‘/n’). Text files are used to store the source code.

Binary Files: Binary files contain data that is stored in a similar manner to how it is
stored in the main memory. Instead of ASCII characters, it is stored in binary format.
The binary files can be created only from within a program and their contents can
only be read by a program.
5. File Handling Functions in C

File is a collection of data that stored on secondary memory like hard disk of a
computer.

The following are the operations performed on files in the c programming language...

 Creating (or) Opening a file


 Reading data from a file
 Writing data into a file
 Closing a file

All the above operations are performed using file handling functions available in C.

(a) Creating (or) Opening a file

 To create a new file or open an existing file, we need to create a file pointer of FILE
type.
 Following is the sample code for creating file pointer.

Syntax: FILE *fp ;


Here fp is file pointer which points to the file.
How to create/open a file?
Whenever you want to work with a file, the first step is to create a file. A file is nothing but s
pace in a memory where data is stored.
To create a file in a ‘C’ program following syntax is used,

FILE *fp;
fp = fopen ("file_name", "mode");

In the above syntax, the file is a data structure which is defined in the standard library.
fopen is a standard function which is used to open a file.
 If the file is not present on the system, then it is created and then opened.
 If a file is already present on the system, then it is directly opened using this function.
For opening a file, fopen() function is used with the required access modes. Some of the
commonly used file access modes are mentioned below.
File opening modes in C:

Note: In the given syntax, the filename and the mode are specified as strings hence they must
always be enclosed within double quotes.

Example:

//C Program to create a file

include<stdio.h>
void main()
{
FILE* fp;
fp = fopen("C:/Users/KESAVARAO/Documents/Files/test.txt","w");
if (fp == NULL)
printf("File is not present");
else
printf("File is created\n");
}
OutPut:
2. How to Close a file?
 One should always close a file whenever the operations on file are over. It means the
contents and links to the file are terminated. This prevents accidental damage to the
file.
 ‘C’ provides the fclose function to perform file closing operation. The syntax of fclose
is as follows,

fclose (file_pointer);

Ex: fclose(fp);

 The fclose function takes a file pointer as an argument.


 It returns 0 if close was successful and EOF (end of file) if there is an error has
occurred while file closing.
 After closing the file, the same file pointer can also be used with other files.

Note: In ‘C’ programming, files are automatically close when the program is terminated. Closing
a file manually by writing fclose function is a good programming practice.

3. How to Writing to a File?


In C, when you write to a file, newline characters ‘\n’ must be explicitly added.
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 ( )

 putc( char, *file_pointer ) - This function is used to write/insert a character to the


specified file when the file is opened in writing mode.

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;
}
Output:

 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;
fp = fopen("MYSAMPLE.txt","w");
putw(66,fp);
i = 100;
putw(i,fp);
fclose(fp);
return 0;
}

Output:
 fprintf( *file_pointer, "text" ) - This function is used to writes/inserts multiple lines
of text with mixed data types (char, int, float, double) into specified file which is
opened in writing mode.

#include<stdio.h>
int main()
{
FILE *fp;
char *text = "\nthis is example text";
int i = 10;
fp = fopen("MYSAMPLE.txt","w");
fprintf(fp,"This is line1\nThis is line2\n%d", i);
fprintf(fp,text);
fclose(fp);
return 0;
}

Output:

 fputs( "string", *file_pointer ) - This method is used to insert string data into
specified file which is opened in writing mode.

#include<stdio.h>
int main()
{
FILE *fp;
char *text = "\nthis is example text";
fp = fopen("MYSAMPLE.txt","w");
fputs("Hi!\nHow are you?",fp);
fclose(fp);
return 0;
}
Output:

 fwrite( “StringData”, sizeof(char), numberOfCharacters, FILE *pointer ) - This function is used to


insert specified number of characters into a binary file which is opened in writing
mode.

Example Program to illustrate fwrite() in C:

#include<stdio.h>
int main()
{
FILE *fp;
char *text = "Welcome to C Language";
fp = fopen("MYSAMPLE.txt","wb");
fwrite(text,sizeof(char),5,fp);
fclose(fp);
return 0;
}

Output:
2. Reading data from a File
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( )

 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.

Example Program to illustrate getc() in C:

#include<stdio.h>
int main()
{
FILE *fp;
char ch;
fp = fopen("MYSAMPLE.txt","r");
printf("Reading character from the file: %c\n",getc(fp));
ch = getc(fp);
printf("ch = %c", ch);
fclose(fp);
return 0;
}

Output:
 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.

Example Program to illustrate getw() in C:


#include<stdio.h>
int main()
{
FILE *fp;
int i,j;
fp = fopen("C:/Users/KESAVARAO/Documents/Files/test.txt.txt","w");
putw(65,fp); // inserts A
putw(97,fp); // inserts a
fclose(fp);
fp = fopen("C:/Users/KESAVARAO/Documents/Files/test.txt.txt","r");
i = getw(fp); // reads 65 - ASCII value of A
j = getw(fp); // reads 97 - ASCII value of a
printf("SUM of the integer values stored in file = %d", i+j);
fclose(fp);
return 0;
}

Output:
 fscanf( *file_pointer, typeSpecifier, &variableName ) - This function is used to
read multiple datatype values from specified file which is opened in reading mode.

Example Program to illustrate fscanf() in C:


#include<stdio.h>
int main(){

char str1[10], str2[10], str3[10];


int year;
FILE * fp;
fp = fopen ("C:/Users/KESAVARAO/Documents/Files/test.txt", "w+");
fputs("We are in 2023", fp);
rewind(fp); // moves the cursor to begining of the file
fscanf(fp, "%s %s %s %d", str1, str2, str3, &year);
printf("Read String1 - %s\n", str1 );
printf("Read String2 - %s\n", str2 );
printf("Read String3 - %s\n", str3 );
printf("Read Integer - %d", year );
fclose(fp);
return 0;
}

Output:
 fgets( variableName, numberOfCharacters, *file_pointer ) - This method is used for
reading a set of characters from a file which is opened in reading mode starting from the
current cursor position. The fgets() function reading terminates with reading NULL
character.

Example Program to illustrate fgets() in C:


#include<stdio.h>
int main(){

FILE *fp;
char *str;
fp = fopen ("MYSAMPLE.txt", "r");
fgets(str,6,fp);
printf("str = %s", str);
fclose(fp);
return 0;
}

Output:

 fread( source, sizeofReadingElement, numberOfCharacters, FILE *pointer ) - This


function is used to read specific number of sequence of characters from the specified file
which is opened in reading mode.

Example Program to illustrate fgets() in C:

#include<stdio.h>
int main(){

FILE *fp;
char *str;
fp = fopen ("MYSAMPLE.txt", "r");
fgets(str,6,fp);
printf("str = %s", str);
fclose(fp);
return 0;
}
Output:
Lab Programs using File Operations in C:

Program 1: Write a C program to copy the content of one file to another file.

#include <stdio.h>
#include <stdlib.h> // For exit()
int main(){
FILE *fptr1, *fptr2;
char filename[100], c;
printf("Enter the filename to open for reading");
scanf("%s",filename);
// Open one file for reading
fptr1 = fopen(filename, "r");
if (fptr1 == NULL){
printf("Cannot open file %s", filename);
exit(0);
}
printf("Enter the filename to open for writing");
scanf("%s", filename);
// Open another file for writing
fptr2 = fopen(filename, "w");
if (fptr2 == NULL){
printf("Cannot open file %s", filename);
exit(0);
}
// Read contents from file
c = fgetc(fptr1);
while (c != EOF){
fputc(c, fptr2);
c = fgetc(fptr1);
}
printf("Contents copied to %s", filename);
fclose(fptr1);
fclose(fptr2);
return 0;
}
Program 2: Write a C Program to Merge the files.

Let the given two files be file1.txt and file2.txt. The following are steps to merge.
1) Open file1.txt and file2.txt in read mode.
2) Open file3.txt in write mode.
3) Run a loop to one-by-one copy characters of file1.txt to file3.txt.
4) Run a loop to one-by-one copy characters of file2.txt to file3.txt.
5) Close all files.

Program:

#include <stdio.h>
#include <stdlib.h>
int main()
{
// Open two files to be merged
FILE *fp1 = fopen("file1.txt", "r");
FILE *fp2 = fopen("file2.txt", "r");

// Open file to store the result


FILE *fp3 = fopen("file3.txt", "w");
char c;
if (fp1 == NULL || fp2 == NULL || fp3 == NULL)
{
puts("Could not open files");
exit(0);
}
// Copy contents of first file to file3.txt
while ((c = fgetc(fp1)) != EOF)
fputc(c, fp3);
// Copy contents of second file to file3.txt
while ((c = fgetc(fp2)) != EOF)
fputc(c, fp3);
printf("Merged file1.txt and file2.txt into file3.txt");
fclose(fp1);
fclose(fp2);
fclose(fp3);
return 0;
}
Program 3: Write a program in C that displays the content of a file in reverse order. The
filename should be entered at run-time .

#include<stdio.h>
#include<string.h>
int main()
{
FILE *fp;
char ch, fname[30], newch[500];
int i=0, j, COUNT=0;
printf("Enter the filename with extension: ");
gets(fname);
fp = fopen(fname, "r");
if(!fp)
{
printf("Error in opening the file...\nExiting...");
return 0;
}
printf("\nThe original content is:\n\n");
ch = getc(fp);
while(ch != EOF)
{
COUNT++;
putchar(ch);
newch[i] = ch;
i++;
ch = getc(fp);
}
printf("\n\n\n");
printf("The content in reverse order is:\n\n");
for(j=(COUNT-1); j>=0; j--)
{
ch = newch[j];
printf("%c", ch);
}

printf("\n");
return 0;
}

You might also like