C Header Files
File handling in C language
Page is under construction
In this article we will learn about file handling in C. In our previous guide we have discussed about file input output in C. We recommend you to see our previous guide to get better experience form this file handling guide.
Before working with files let’s have a look at different library functions related to file handling in C.
- fopen() — fopen() is used to open a new file. If the file does not exist, then it will create the file and open it.
- fclose() — fclose() is used to close the opened file.
- fprintf() — fprintf() is used to write data to the file.
- fscanf() — fscanf() function is use to read data from the file.
- fputc() — It is used to write a character to the file.
- fgetc() — fgetc() is used to read a character for the file.
- fputw() — fputw() can write any integer to the file.
- fgetw() — It is used to read any integer from the file.
- fseek() — fseek() is use to point our expected position. It sets the pointer to the given position.
- ftell() — We use ftell() when we need to know the current position inside a file.
- rewind() — rewind() is used when we need to set the file pointer at the beginning of our file.
Opening and closing of a file
fopen() and fclose() functions for file handling
fopen() is use to open a file. Whenever we work with a file, at first we need to open it. this fopen() function takes two parameters. One is the directory of our expected file and other is the opening mode which we have discussed in our previous guide.
On the other hand we use fclose() function to close a file after we have completed all our operations to the file. See the following example that how we can open and close a file using fopen() and fclose() function.
// code here 1st
The program will create a file named example file.txt in your current directory.
Reading and writing in a file (file handling guide)
fprintf() and fscanf() functions
fprintf() function is use to write a set of characters to the file where fscanf() is used to read the set of characters from the file. fscanf() returns EOF(end of file) at the end of the file.
Let’s see a program to learn about fprintf() and fscanf() function.
// code here 2nd
Reading and writing a character in a file
fputc() and fgetc() functions for file handling
We can write a single character using fputc() function and read a single character using fgetc() function. fgetc() function also returns EOF at the end of the file. See the following example of C program to learn about fputc() and fgetc() functions.
// code here 3rd
You will see the following output after compiling and running the above program.
// output window
Hope, you have got a better idea about file handling in C. If you have any doubt about file handling still now, then discuss it on our discussion section.