File Handling in C Programming Language with Programs/Examples.

C Program’s output do not permanent, it stores the values in the primary memory that is volatile memory. When you run your program again, previous values do not exist.

C Language allows you to save values of the variable (data of your program at the run time) in the files. File handling means to handle file operating using some library functions creating, opening, editing and accessing files.

File Handling in C programming Language with Programs

Files in C Language

Files are the sequence of bytes stored in secondary memory (external memory) device like hard disk, compact disk, pen drive etc. These files are permanent in the memory and you can access any time when ever you need it.

There are basically two types of files: Text Files and Binary Files. Text files are those file which store in the memory in ASCII format, user can read the contents of those file very easily. While Binary files are those files which store in the memory in Binary (Byte) format, user can not read them as they are not in ASCII format.

C Language provides following functions to operate a file, these functions declared in stdio.h header file, the functions are:

Functions Description
fopen() Open/Create a file.
fclose() Close an opened file.
fgetc/getc() Read/Get a character from file.
fputc/putc() Write/Put a character into the file.
getw() Read/Get an integer from file.
putw() Write/Put an integer into file.
fgets() Read/Get string from file.
fputs() Write/Put string into file.
fscanf() Read/Get mixed data from file.
fprintf() Write/Put mixed data into file.
fread() Read/Get an object (structure) from file.
fwrite() Write/Pet an object (structure) into file.
ftell() To return current position of file pointer.
fseek() To move file pointer at specified location from current, beginning and end position.
rewind() Set the position to the beginning of the file.
rename() To rename a file.
remove() To remove a file from the memory.

File Pointer (FILE*)

FILE is a structured declared in stdio.h, which is used to store address (first byte’s address) of the file. If file opens/ creates successfully FILE stores a memory address where file is created otherwise it conatins NULL.

FILE *file-pointer;
FILE *fp;

Here, FILE is a predefined structure and *fp is a pointer of FILE.

fopen() and fclose()

fopen() opens/ creates a file in Read, Write, Append, Read and Write, Append and Read mode.

file-pointer= fopen(const char *file-name, const char *file-mode);
fclose(file-pointer);

  • file-name is the name of the file to create or open.
  • file-mode is the file mode in which file being opening or creating.
  • fopen() return address of the file if created else returns NULL if not created.

There are following file modes:

Mode Description
r To open file in read mode.
w To open file in write mode.
a To open file in append mode.
r+ To open file in read and write mode.
w+ To open file in write and read mode.
a+ To open file in append and read mode.
rb, wb, ab, rb+, wb+, ab+ To open file in binary format.

Consider the example

#include<stdio.h>
#include<stdlib.h> // for exit(1) function

int main()
{
	FILE *fp;
	fp=fopen("file1.txt","w");
	if(fp==NULL)
	{
		printf("\nError in opening file.");
		exit(1);	// to exit from program
	}
	printf("\nFile created successfully.");
    fclose(fp);	// to close file
    return 0;
}

    
    File created successfully.

file1.txt will be created at the current directory in write mode.

fgetc() and fputc()

fputc() – Is used to write a single character into file.

fgetc() – Is used to read a single character from file.

fputc(char character, FILE *file-pointer);
char fgetc(FILE *file-pointer);
Consider the example

#include<stdio.h>
#include<stdlib.h> // for exit(1) function

int main()
{
    
	FILE *fp;
	char ch;

	fp=fopen("file1.txt","w");
	if(fp==NULL)
	{
		printf("\nError in opening file.");
		exit(1);	// to exit from program
	}
	printf("\nFile created successfully.");
	fputc('A',fp); // write 'A'
	fputc('B',fp); // write 'B'
	fputc('C',fp); // write 'C'

	fclose(fp);	// to close file
	printf("\nFile saved and closed.");

	/*Open file in read mode*/
	fp=fopen("file1.txt","r");
	if(fp==NULL)
	{
		printf("\nError in opening file.");
		exit(1);	// to exit from program
	}
	printf("\nFile opened.\nFile's contents : ");

	/*reading from file*/
	ch=fgetc(fp);	    printf("%c",ch);
	ch=fgetc(fp);	    printf("%c",ch);
	ch=fgetc(fp);	    printf("%c",ch);
	    
    fclose(fp);
	printf("\nFile closed.");

    return 0;
}

    File created successfully.
    File saved and closed.
    File opened.
    File's contents : ABC
    File closed.

Example to write and read a complete text file.


#include<stdio.h>
#include<stdlib.h> // for exit(1) function

int main()
{
    
	FILE *fp;
	char ch;

	fp=fopen("file1.txt","w");
	if(fp==NULL)
	{
		printf("\nError in opening file.");
		exit(1);	// to exit from program
	}
	printf("\nFile created successfully.");

	printf("\nEnter text here (press # to close) :\n");
	while( (ch=getchar()) !='#')
	{
		fputc(ch,fp);
	}

	fclose(fp);	// to close file
	printf("\nFile saved and closed.");

	/*Open file in read mode*/
	fp=fopen("file1.txt","r");
	if(fp==NULL)
	{
		printf("\nError in opening file.");
		exit(1);	// to exit from program
	}
	printf("\nFile opened.\nFile's contents :\n");

	/*reading from file*/
	while( (ch=fgetc(fp))!=EOF)
	{
		printf("%c",ch);
	}
	printf("\n\nFile closed.");

    return 0;
}
    File created successfully.
    Enter text here (press # to close) :
    Hello Guys!
    This is a Free Online Tutorial Website.
    Enjoy learning... #

    File saved and closed.
    File opened.
    File's contents : 
    Hello Guys!
    This is a Free Online Tutorial Website.
    Enjoy learning...

    File closed.

while( (ch=getchar()) !='#') statement will read character from keyword until # is not found. and while( (ch=fgetc(fp))!=EOF) statement will read character from file until EOF (End of File) is not found.

getw() and putw()

getw() – Is used to put/write integer in the file.

putw() – Is used to get/read integer from the file.

putw(int number, FILE *file-pointer);
int getw(FILE *file-pointer);
Consider the example
#include<stdio.h>
#include<stdlib.h> /* for exit(1) function*/
    
int main()
{
	FILE *fp;
	int num,iLoop;

	fp=fopen("file.dat","wb");
	if(fp==NULL)
	{
		printf("\nError in opening file.");
		exit(1);/* to exit from program*/
	}

	
	for(iLoop=0;iLoop < 10; iLoop++)
	{
		printf("Enter number [ %02d ] :",iLoop+1);
		scanf("%d",&num);
		putw(num,fp); /*write num into the file*/
	}
	fclose(fp);

	/*Open file to read*/
	fp=fopen("file.dat","rb");
	if(fp==NULL)
	{
		printf("\nError in opening file.");
		exit(1);/* to exit from program*/
	}

	printf("\nEntered numbers are :\n");
	for(iLoop=0; iLoop < 10; iLoop++)
	{
		num=getw(fp);
		printf("\%d,",num);
	}
	fclose(fp);
    return 0;
}
    Enter number [ 01 ] :11
    Enter number [ 02 ] :22
    Enter number [ 03 ] :33
    Enter number [ 04 ] :44
    Enter number [ 05 ] :55
    Enter number [ 06 ] :66
    Enter number [ 07 ] :77
    Enter number [ 08 ] :88
    Enter number [ 09 ] :99
    Enter number [ 10 ] :111

    Entered numbers are :
    11,22,33,44,55,66,77,88,99,111,

You have to open file into binary mode, if you are using getw() and putw() functions.

fputs() and fgets()

fputs() – Is used to write a complete string in the file.

fgets() – Is used to read a string (number of character, you can define) from the file.

fputs(char *buffer, FILE *file-pointer);
fgets(char *buffer, int length, FILE *file-pointer);
Consider the example
#include<stdio.h>
#include<stdlib.h> /* for exit(1) function*/
#include<string.h>

int main()
{
    FILE *fp;
    char text[50];
 
    fp=fopen("file.txt","w");
    if(fp==NULL)
    {
        printf("\nError in opening file.");
        exit(1);/* to exit from program*/
    }
 
	strcpy(text,"This is line 1.");
	fputs(text,fp);
	fputc('\n',fp);			/*writting new line (\n) after the string*/
	strcpy(text,"This is line 2.");
	fputs(text,fp);
	fputc('\n',fp);			/*writting new line (\n) after the string*/
   
	fclose(fp);
    fp=fopen("file.txt","r");
    if(fp==NULL)
    {
        printf("\nError in opening file.");
        exit(1);/* to exit from program*/
    }
 
	fgets(text,20,fp);		/*20 is the maximum characters to read*/
	printf("%s\n",text);
	fgets(text,20,fp);		/*20 is the maximum characters to read*/
	printf("%s\n",text);
	fclose(fp);
	    
    return 0;
}
    This is line 1.

    This is line 2.

fprintf() and fscanf()

fprintf() – Is used to write mixed data in the file.

fscanf() – Is used to read mixed data from the file.

int fprintf(FILE *file-pointer, const char *format, variable-list);
int fscanf(FILE *file-pointer, const char *format, &variable-list);
Consider the example

#include<stdio.h>
#include<stdlib.h> /* for exit(1) function*/
#include<string.h>

int main()
{
    FILE *fp;
    char	name[30],temp[30];
	int		age;
	float	perc;
	int		result;
 
    fp=fopen("file.txt","wb");
    if(fp==NULL)
    {
        printf("\nError in opening file.");
        exit(1);/* to exit from program*/
    }
 
	/*padding 30 bytes with space, you have to put 30 bytes for name*/
	memset(name,' ',30);
	printf("Enter Name :"); gets(temp);
	memcpy(name,temp,strlen(temp));	/*copy temp to name with space padded*/
	printf("Enter Age  :"); scanf("%d",&age);
	printf("Enter Percentage :"); scanf("%f",&perc);

	/*write data into file*/
	result= fprintf(fp,"%s,%d,%f",name,age,perc);
	if(result)
		printf("\nData inserted successfully.");
	fclose(fp);

	/*re open file in read mode*/
	fp=fopen("file.txt","rb");
    if(fp==NULL)
    {
        printf("\nError in opening file.");
        exit(1);/* to exit from program*/
    }

	/*reading data from file*/
	result=fscanf(fp,"%s,%d,%f",name,&age,&perc);
	if(result)
		printf("\nData from file :\nName: %s, Age: %d, Percentage:%f",name,age,perc);
	else
		printf("\nData reading failed.");
   
	fclose(fp);
    return 0;
}
    Enter Name :Jassy
    Enter Age  :23
    Enter Percentage :75.50

    Data inserted successfully.
    Data from file :
    Name: Jassy, Age: 23, Percentage:75.500000

fwrite() and fread()

These functions are good to use when you have mixed data, declare them into a structure and write/read in/from the file. These functions operate with an object like structure, union and class (in case of c++).

fwrite() – Is used to write object(s) in the file.

fread() – Is used to read object(s) from the file.

You can also read/write multiple objects at a time from/in the file. File should be created as binary mode.

int fwrite(const void *buffer, int size, int count, FILE *file-pointer);

const void *buffer - Buffer to write in the file, should be cast type as char*.
int size - Size to write in the file.
int count - Number of objects to write in the file.
FILE *file-pointer - File pointer to write.

int fread(void *buffer, int size, int count, FILE *file-pointer);

void *buffer - Buffer to read from the file, should be cast type as char*.
int size - Size to read from the file.
int count - Number of objects to read from the file.
FILE *file-pointer - File pointer to read.

Consider the example
#include<stdio.h>
#include<stdlib.h> /* for exit(1) function*/
#include<string.h>

typedef struct 
{
	char	name[30];
	int		age;
	float	perc;
}student;

int main()
{
    FILE	*fp;
    student std; /*std - student structure's variable*/
	int		result;
 
	
    fp=fopen("file.txt","wb");
    if(fp==NULL)
    {
        printf("\nError in opening file.");
        exit(1);/* to exit from program*/
    }
 
	/*Input student detail*/
	printf("Enter Name	: "); gets(std.name);
	printf("Enter Age	: "); scanf("%d",&std.age);
	printf("Enter Percentage: "); scanf("%f",&std.perc);

	/*writting in the file*/
	result=fwrite((char*)&std,sizeof(std),1,fp);
	
	if(result)
		printf("\nData inserted successfully.");
	fclose(fp);

	/*re open file in read mode*/
	fp=fopen("file.txt","rb");
    if(fp==NULL)
    {
        printf("\nError in opening file.");
        exit(1);/* to exit from program*/
    }

	/*reading data from file*/
	result=fread((char*)&std,sizeof(std),1,fp);	
	if(result)
		printf("\nData from file :\nName: %s, Age: %d, Perc:%f",std.name,std.age,std.perc);
	else
		printf("\nData reading failed.");
   
	fclose(fp);

    return 0;
}
    Enter Name      : Jossu Dutta
    Enter Age       : 23
    Enter Percentage: 75.50

    Data inserted successfully.
    Data from file :
    Name: Jossu Dutta, Age: 23, Perc:75.500000
Consider the example to Read and Write multiple objects
#include<stdio.h>
#include<stdlib.h> /* for exit(1) function*/
#include<string.h>

typedef struct 
{
	char	name[30];
	int		age;
	float	perc;
}student;

int main()
{
    FILE	*fp;
    student std; /*std - student structure's variable*/
	int		result,n,iLoop;
 
	
    fp=fopen("file.txt","wb");
    if(fp==NULL)
    {
        printf("\nError in opening file.");
        exit(1);/* to exit from program*/
    }
 
	printf("\nEnter total number of students :");
	scanf("%d",&n);

	/*Input student detail*/
	for(iLoop=0; iLoop < n; iLoop++)
	{
		printf("\nEnter details of student [%d] :\n",iLoop);
		printf("Enter Name	: "); 
		fflush(stdin);
		gets(std.name);

		printf("Enter Age	: "); 
		scanf("%d",&std.age);

		printf("Enter Percentage: "); 
		scanf("%f",&std.perc);
	
		/*writting in the file*/
		result=fwrite((char*)&std,sizeof(std),1,fp);
		if(result==0) break;
	}

	if(result)
		printf("\nData inserted successfully.");
	fclose(fp);

	/*re open file in read mode*/
	fp=fopen("file.txt","rb");
    if(fp==NULL)
    {
        printf("\nError in opening file.");
        exit(1);/* to exit from program*/
    }

	/*reading data from file*/
	printf("\n\nEntered Records are :\n");
	while((result=fread((char*)&std,sizeof(std),1,fp)))
	{
		if(result)
			printf("\nName: %s, Age: %d, Percentage:%f",std.name,std.age,std.perc);
	}
   
	fclose(fp);
    return 0;
}
    
    Enter total number of students :3

    Enter details of student [0] :
    Enter Name      : Satendra
    Enter Age       : 16
    Enter Percentage: 88.00

    Enter details of student [1] :
    Enter Name      : Rahul
    Enter Age       : 15
    Enter Percentage: 89.75

    Enter details of student [2] :
    Enter Name      : Divakar
    Enter Age       : 17
    Enter Percentage: 90

    Data inserted successfully.

    Entered Records are :

    Name: Satendra, Age: 16, Percentage:88.000000
    Name: Rahul, Age: 15, Percentage:89.750000
    Name: Divakar, Age: 17, Percentage:90.000000

ftell()

ftell() return the current position of the file pointer.

long int ftell(FILE *file-pointer);
printf("Current position is : %d",ftell(fp));

fseek()

fseek() is used to move the file pointer’s position at the specified position from the Current position, End and the Beginning.

int fseek(FILE *file-pointer, long int offset, int origin);

FILE *file-pointer - File pointer in which, you want to move pointer's position.
long int offset - Number of bytes to move.
int origin - Origin is the position from where you want to move.

There are following origins:

Flag Value Description
SEEK_SET 0 From the beginning.
SEEK_CUR 1 From the current position.
SEEK_END 2 From the end.
fseek(fp,10,SEEK_SET);

File pointer will move 10 bytes forward from the beginning of the file.

fseek(fp,-10,SEEK_CUR);

File pointer will move 10 bytes backward from the current position of the file pointer.

fseek(fp,-10,SEEK_END);

File pointer will move 10 bytes backward from the end of the file.

Consider the example using ftell(), fseek() and Opening file in “w+” mode (write and read both)

#include<stdio.h>
int main()
{
    FILE	*fp;
	int		ch;
    
    fp=fopen("file.txt","w+");
    if(fp==NULL)
    {
        printf("\nError in opening file.");
        exit(1);/* to exit from program*/
    }
 
	/*writting A to Z in the file*/
	for(ch='A'; ch <= 'Z'; ch++)
	{
		fputc(ch,fp);
	}

	printf("\nCurrent file pointer's position : %d",ftell(fp));
	/*Reading file from the beginning */
	fseek(fp,0,SEEK_SET);
	printf("\nText from beginning:\n");
	while( (ch=fgetc(fp))!=EOF)
	{
		printf("%c",ch);
	}
		
	fseek(fp,-10,SEEK_END);
	printf("\nAfter -10 bytes from SEEK_END, file pointer's position : %d",ftell(fp));
	printf("\nText from -10 bytes backward :\n");
	while( (ch=fgetc(fp))!=EOF)
	{
		printf("%c",ch);
	}
	fclose(fp);

    return 0;
}


    Current file pointer's position : 26
    Text from beginning:
    ABCDEFGHIJKLMNOPQRSTUVWXYZ
    After -10 bytes from SEEK_END, file pointer's position : 16
    Text from -10 bytes backward :
    QRSTUVWXYZ

rename() and remove()

rename() - Is used to rename a file.

remove() - Is used to remove/delete a file.

int rename(const char *old-file-name, const char *new-file-name);
int remove(const char *file-name);
Consider the example
#include<stdio.h>
int main()
{
    FILE	*fp;
	
	fp=fopen("d:/file1.txt","w");
	if(fp==NULL)
	{
		printf("\nFile to create, file name : %s","d:/file1.txt");
	}
	else
	{
		printf("\nFile created, file name : %s","d:/file1.txt");
	}
	fclose(fp);

	/*rename file1.txt to file2.txt*/
	rename("d:/file1.txt","d:/file2.txt");

	/*open file1.txt in read mode*/
	fp=fopen("d:/file1.txt","r");
	if(fp==NULL)
	{
		printf("\nFailed to open, file name : %s","d:/file1.txt");
	}
	else
	{
		printf("\nFile opened, file name : %s","d:/file1.txt");
		fclose(fp);
	}
	

	/*open file2.txt in read mode*/
	fp=fopen("d:/file2.txt","r");
	if(fp==NULL)
	{
		printf("\nFailed to open, file name : %s","d:/file2.txt");
	}
	else
	{
		printf("\nFile opened, file name : %s","d:/file2.txt");
		fclose(fp);
	}

	/*remove file2.txt*/
	remove("d:/file2.txt");
	
	/*open file2.txt in read mode*/
	fp=fopen("d:/file2.txt","r");
	if(fp==NULL)
	{
		printf("\nFailed to open, file name : %s","d:/file2.txt");
	}
	else
	{
		printf("\nFile opened, file name : %s","d:/file2.txt");
		fclose(fp);
	}
    return 0;
}
    File created, file name : d:/file1.txt
    File opened, file name : d:/file1.txt
    File opened, file name : d:/file2.txt
    Failed to open, file name : d:/file2.txt




Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.