Steps to create a data file in C
1. File Pointer Declaration
File pointer is a pointer variable of predefined structure FILE. When we need to store some data in a file, we have to specify the name of data file by using its file pointer variable.
We can declare a file pointer variable as :
2. Opening a file
We need to use predefined function fopen() to open a file in a C program.
Fname represents name of file to be opened.
Mode refers to various modes available for opening a file are:
|r||File opened for reading.|
|w||Create a file.|
|a||Open file in append mode. New contents gets added at end of the file.|
|r+||Open file for both reading and writing.|
|w+||Open file for both writing and reading.|
|a+||Open file for both writing and reading.|
|wb||Create a binary file|
|rb||Open a binary file for reading.|
|ab||Open a binary file to add new contents at the end of the file|
3. Reading or writing data in the file
When a file is opened in any of the modes among “w”, ”w+”, ”a” or “a”+. It will be created if it does not already exist.
When a file is opened in mode “r”, ”r+”. we can read contents of file.
4. Closing the file
We need to close file after performing required operations on it. Function fclose( ) can be used to close the file.
Syntax of fclose() function is:
Fpointer represents file pointer variable.