header ads

File Handling in C || CodeTextPro

File Handling in C Programming

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

In C language, we use a structure pointer of the 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,

file handling in c

Opening a File or Creating a File

fp= fopen( file_name, file_mode)

file handling in c

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.

FILE *fp;
char ch;
fp = fopen("one.txt", "w");
printf("Enter data");
while( (ch = getchar()) != '$') {
fp = fopen("one.txt", "r");
while( (ch = getc(fp)! = EOF)

Note: This program will read the input character-wise from the user until a '$' is pressed. Then display the contents of the file in the console.

File Handling in C Programming

Reading and Writing from File using fwrite() and fread()

** C program to write all the members of an array of structures to a file using fwrite(). Read the array

from the file and display on the screen.

#include <stdio.h>
struct student
char name[50];
int height;
int main(){
struct student stud1[5], stud2[5];
FILE *fptr;
int i;
fptr = fopen("file.txt","wb");
for(i = 0; i < 5; ++i)
printf("Enter name: ");
printf("Enter height: ");
scanf("%d", &stud1[i].height);
fwrite(stud1, sizeof(stud1), 1, fptr);
fptr = fopen("file.txt", "rb");
fread(stud2, sizeof(stud2), 1, fptr);
for(i = 0; i < 5; ++i)
printf("Name: %s\nHeight: %d", stud2[i].name, stud2[i].height);


If you want to download file handling in c pdf file clicks the link below.

File Handling in C PDF

Post a Comment