Basics of file handling in C language

Basics of file handling in C language

There are two types of files, which can be handled through C programming language:

  • Character Oriented File Handling/Text files
  • Binary Oriented File Handling/Binary files

For file handling, we use a structure named “FILE” which is declared in stdio.h header file.

Some important and most useful file handling functions:

fgetc – It is used to read single character from the file.

fputc – It is used to write a single character in the file.

fputw – It is used to write an integer in the file.

fgetw – It is used to read an integer from the file.

fscanf – It is used to read formatted data (like integer, char, float etc) from the file.

fprintf – It is used to write formatted data (like integer, char, float etc) in the file.

fwrite – It is used to write mixed data (structure) in the file.

fread – It is used to read mixed data (structure) from the file.

fopen – It is used to open a file in various modes, here we are using “w” mode that means file is open in write mode only. Later, in the program, We have used “r” that means file is open in read mode only.

fclose – It is used to close an opened file. You must use this function before existing the program.

 

The following actions we are going to cover in this article:

  • Creating variable of file pointer
  • Opening/creating a file
  • Write some of the characters in a file
  • Reading one by one character from a file
  • Closing a file

Let’s see the below program

#include <stdio.h>
int main()
{
 
    FILE *fp;   /* file pointer*/
    char fName[50];
 
    printf("\nEnter file name to create :");
    scanf("%s",fName);
 
    /*creating (open) a file*/
    fp=fopen(fName,"w");
    /*check file created or not*/
    if(fp==NULL)
    {
        printf("Error : File does not created!!!");
        exit(0); /*exit from program*/
    }
 
    printf("Success: File created successfully.");
    /*writting into file*/
    putc('S',fp);
    putc('A',fp);
    putc('T',fp);
    putc('Y',fp);
    putc('A',fp);
printf("\nData written successfully."); 
fclose(fp); /*again open file to read data*/ 
fp=fopen(fName,"r"); 
if(fp==NULL) 
{
printf("\nCan't open file!!!");
exit(0);
}
printf("Contents of file is :\n"); 
printf("%c",getc(fp));
printf("%c",getc(fp));
printf("%c",getc(fp));
printf("%c",getc(fp));
printf("%c",getc(fp));
fclose(fp); 
return 0; 
}

Output

Enter file name to create : test.txt
File created successfully.
Data written successfully.
Contents of file is :
SATYA

 

 

Leave a Reply