Steps to create a data file in C

Preview
You must first complete Data File Handling in C before viewing this Lesson



Steps to create a data file in C

1. Declaration of file pointer variable

File pointer is 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 :

FILE *f;



2.  Opening a file

We need to use predefined function fopen() to open a file program.

Syntax:

fopen(Fname,Mode);

Fname represents name of file to be opened.

Mode refers to various modes available for opening a file are:

Mode                    Explanation
             rTo open a file for reading.
            wCreate a file.
             aOpen 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.
            wbCreate a binary file
             rbOpen a binary file for reading.
            abOpen 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:

fclose(Fpointer) ;

Fpointer represents file pointer variable.



Best Books of C

Lesson tags: Closing the file in c, Declaring a file pointer in c, End of file(EOF) in c, Opening a file in c, Reading or writing data in the file in c, Steps to create a data file in a C, The Null Pointer or Character in c
Back to: C Programming Language