Explain defineing and opening file in C with example

How to define and open file in C 


DEFINING AND OPENING A FILE :


Data structure of a file is defined as FILE in the library of standard I/O function
definitions. Therefore all the file should be declared as type FILE before they are used.
FILE is defined data type.
When we open a file, we  must specify what we want to do with the file. For example we
may write data to the file or read the already existing data.

General format for declaring and  opening a file:


•    The first statement declares the variable fp as a “pointer to the data type FILE”
•    The second statement opens the file named filename and assigns an identifier to the
      FILE type pointer fp.
•    Mode can be one of the following :

                     r          Open the file for reading only.
                   w        Open the file for writing only.   
                   a        Open the file for reading only.

     Many recent compirs includes additional modes of operation. They include:

                      r+                The existing file is opened to the beginning for both reading
                                          and  writing
                      w+               Same as w except for both reading and writing.
                      a+               Same as a except for both reading and writing.


When trying to open a file, one of the following things may happen:

1.    When the mode is ‘writing’, a file with the specified name is created  if the file does not exist. The content are deleted if the file already exists.
2.    When the purpose is ‘appending’, the file is opened with the current contents safe. A file with the specified name is created if the file does not exist.
3.    If the purpose is ‘reading’ , and if it exists, then the file is opened with the current contents safe; otherwise an error occurs.

Labels: