Home »
C programming language
Basics of file handling with writing and reading text in C language
Learn: In this article, we are going to learn basics of file handling in C language with example to write and read text in/from a file.
Submitted by Ridhima Agarwal, on October 01, 2017
In C language, file handing is used to manage files in secondary memory, by using file handling function, we can create, read, remove, copy etc files in/from secondary memory. To perform complete file operations, we use file handling.
Type of files (file handling)
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.
Let's have a look of some of the 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.
Writing and reading data in/from file in C language
In this program, we will learn how we can write a file (using character by character) and how can we read all data of a file (character by character) in C language?
For this, we use two functions 1) fgetc – to read single character from the file and 2) fputc – to write single character in file.
Other functions/variables that are used to handle a file:
1) fopen - It is used to open a file in various modes, here I am using “w” mode that means file is open in write mode only. Later, in the program, I used “r” that means file is open in read mode only.
2) fclose - It is used to close an opened file. You must use this function before existing the program.
find program here...