Files I/O
Files I/O
The first and foremost thing we should know when working with files in C is that we have to declare a pointer of the file type to work with files. The syntax for declaring a pointer of file type is
Modes
Functions and their modes of declarations are two important factors of file handling. We have to learn about different modes used along with these functions as a parameter. The following are the modes:
- r: opens a file for reading.
- w: opens a file for writing. It can also create a new file.
- a: opens a file for appending.
- r+: opens a file for both reading and writing but cannot create a new file.
- w+: opens a file for both reading and writing.
There are many other modes, but these are the basic and most used ones.
Closing a file
When working with C, closing open files is an essential step. A programmer often makes a mistake of not closing an open file. This becomes crucila because files do not automatically get closed after a program uses them. The closing has to be done manually.
To close a file, we have to use the fclose() function. We only need to pass the pointer as a parameter to the function.
Syntax:
Reading a file
Reading from a file is as easy as reading any other stuff as an input in C. We just use a file version of scanf(). In order to read from a file, we use the function fscanf(). Like scanf() used to get input from the keyboard, it gets its input from a file and prints it onto the screen.
We have to send the file pointer as an argument for the program to be able to read it. The file has to be opened in r mode, i.e., read mode, to work properly for fscanf().
Example:
The file example.txt had “Welcome_To_CodeWithHarry!” as its content, hence the output:
Writing to a file
Writing to a file is as easy as printing any other stuff in C. We just use a file version of printf(). In order to write to a file, we use the function fprintf(). For printing text inside the file, we use fprintf() as we did for printing text on the screen using printf(). We have to send the file pointer as an argument for the program to be able to print it into the file. The file has to be opened in w mode, i.e. write mode, to be able to write in the file properly.
fprintf() takes the pointer to the file as one of the arguments along with the text to be written.
Example:
Output in the example.txt file: