File Handling in c


1.What is File handling in C ?

Ans: File handling in C is the process in which we create, open, read, write, and close operations on a file. C language provides different functions such as fopen(), fwrite(), fread(), fprintf(), etc. to perform input, output, and many different C file operations in our program.

Syntax  : *ptr=fopen("filename","Mode")


ModeDescription
rOpens an existing text file for reading
WOpens a file for writing. If it doesn't exist, then a new file is created. Writing starts from the beginning
of the file.
aOpens a text file for writing in appending mode. If it does not exist, then a new file is created.
The program will start appending content to the existing file content.
This mode will open a text file for both reading and writing
w+Opens a text file for both reading and writing. It first truncates the file to zero length If it exists,
otherwise creates a file If it does not exist.
a+Opens a text file for both reading and writing. It creates the file if it does not exist. The reading
will start from the beginning but writing can only append to file.

Various Functions of file handling in c.

1. fputc()  : This function is used to insert a single character in the file. 
2. fputs () : This function is used to insert a string in a file.
3. fgetc()  : This function is used to print the first character of a file
4. fgets()  :  This function is used to print the first string or a string of specific given size.

1. WAP to open a file.

#include <stdio.h>
#include <stdlib.h>

int main()
{
    
    FILE* fptr;

    fptr = fopen("filename.txt", "r");

 
    if (fptr == NULL) 
{
        printf("The file is not opened. The program will "
               "now exit.");
        exit(0);
    }

    return 0;
}

 Output :




2. WAP to create a file and write and close it.

#include <stdio.h> 
#include <stdlib.h> 
int main()
 { 
int num; 
FILE *fptr; 
fptr = fopen("program.txt","w");
 if(fptr == NULL) 
{
 printf("Error!");
 exit(1);
 }
 printf("Enter num: ");
 scanf("%d",&num);
 fprintf(fptr,"%d",num);
 fclose(fptr); 
 return 0;
 }

 Output :