Skip to main content

Opening and closing a file in C language

Opening a file

As discussed earlier whenever the file manipulation is to be performed the logical file is attached to the physical file. It means the file pointer holds the address of physical file. This can be achieved by means of opening a file. This operation is also called as linking a logical file with physical file. The fopen() function is used to link the logical file with that of physical file.

The file is opened to perform read/write operations on it and it is promptly closed to indicate the completion of the desired read/write operations.

The syntax of the function fopen() is as follows:

filepointervariable = fopen(“physicalfilename”,”openingmode”);

Here, filepointervariable represents a pointer variable of FILE data type. Physicalfilename represents a name of the  physical file (a string variable or constant). Openingmode represents one of the available modes (a string constant).
The filepointervariable may be any of the file pointers as discussed in the earlier article. The physicalfilename is a string constant or a variable used to represent name of the physical file. The file may be an existing one or a new one that is to be created. The write operations can be performed on any new file and both read/write operations can be performed on an existing file. The openingmode is also a string constant that indicates the operations to be performed on new or existing file.

The following table provides the list of file opening modes available which are used as string constants like “m” where m is the mode:
table provides the list of file opening modes

The Following table provides the "flags" of the streams (which are defined in FILE structure)
table provides the "flags" of the streams

Consider the following declaration and file opening statement:
 FILE *fpl;

fpl=fopen(“physicalfilename”,”openingmode”);

The fopen() function links the logical file ‘fpl’ with the physical file ‘physicalfilename’. The 'openingmode’ indicates the operation mode as per the table shown above. One of them is selected as per the requirements. If the file is created for the first time then either “w” or “a” can be selected. When the data to be transferred is in binary format the mode “wb” or “ab” can be selected.

 The header file ’stdio.h’ contains declarations for the file I/O and should always be included at the very beginning of C programs that use ‘data files’. The constants such as EOF, NULL, etc. are also defined in ’stdio.h’. If the physical file mentioned is successfully opened then the logical file is linked with it otherwise the function fopen() returns NULL. This NULL value helps in testing the successful  opening of any physical file for the respective operation. In case of failure to open the file, proper error message can be displayed indicating “file opening error” may be along with the filename.

Consider another statement like: fp = fopen(“prog.c”, “r”);

Here “prog.c” is the physical file that is opened. It is opened in ‘read’ mode. So, the above statement opens a file called “prog.c” (a physical file) for reading and associates the file pointer fp(logical file) with it. Note here that the file opened is a text file. If the file “prog.c” exists then it is  successfully opened and a valid address is stored in “fp” otherwise a NULL is stored in the file pointer “fp”. In such case an error can he reported like:
if(fp = NULL)

{

printf(“Error in opening the file..");
 exit(l);

}

If “emp.dat” file is to be created for the first time and the data is to be written in binary format then the statement used to do so is:
 fp = fopen( “emp.dat”, “wb”) ;

By chance if the file “emp.dat” already exists then the contents of it are erased and the new data is transferred after every write operation. To retain the data and write the data at the end the file opening mode is changed like:

fp = fopen( “emp.dat”, “ab”) ;

Once the file is open in the respective mode then it is ready for either input (read) or output (write) or append (write at the end) operation.

Closing a file


As discussed earlier the file is opened for input or output operations. After either of the operations it is required to close the opened file to ensure the detachment of physical file. Of course this detachment is done automatically by the system when the program execution is over. To ensure the completeness of the program every programmer must close the opened file in the file handling programs. In order to reuse the file pointer variable declared, to open another file, it is must to close the earlier physical file that is already attached. The closing of file is basically related to closing the logical file that indirectly closes the physical file for I/O operations.

To close a file simply the function fclose(filepointer) is used with the file pointer as the parameter to close a single file. If more than one files are to be closed at a time then the function fcloseall() is used without any parameters.

You can open a file for writing, close it, and reopen it for reading, then close it, and open it again for appending, etc. Each time you open it, you could use the same file pointer. Of course it is the better way of using same file pointer all the time. If more than one file is simultaneously to be operated then different file pointers are required. The file pointer is simply a tool that you use to point to a file and you decide what file it will point to.

The following statements show the usage of the functions used for closing the files:
 FILE *fpl;

fp 1 =fopen(“emp.dat”,”w”); /* the logical file fpl linked to physical file emp.dat in WRITE mode */
................
 /* Write operations on the file*/
 ................

fclose(fpl); /* The file is closed */
 fpl=fopen(“trans.dat”,”r”); /* the logical file fpl linked to physical file trans.dat in READ mode */
 .....................
/* Read operations on the file*/
......................
fclose(fpl); /* The file is closed */

In the above description the logical file fpl is closed before linking it with another physical file.

In the next description more than one file pointer usage and fcloseall() to close all the opened files simultaneously can be observed.

 FILE *fpl, *fp2, *fp3;

fp1 =fopen(“emp.dat”,”a”); /* the logical file fpl linked to physical file emp.dat in APPEND mode*/
fp2=fopen(“transl.dat”,”r”); /* the logical file fp2 linked to physical file transl.dat in READ mode*/
fp3=fopen(“trans2.daf","r”); /* the logical file fp3 linked to physical file trans2.dat in READ mode*/
....................

/* Simultaneously Read operations on the files fp2 and fp3 and Write operations on the file fp4 */
....................

fcloseall(); /* all the three files are closed at a time */

The observation from above two descriptions provide the usage of the parameter in flcose() and non-usage in fcloseall().

Comments

Popular posts from this blog

difference between structure and union in C Language

In c language article we will see the difference between union and structure. Both are the user define datatype in c language. See the table which is mentioned below: ASP.NET Video Tutorial Series Structure Union1.The keywordstruct is used to define a structure 1. The keyword union is used to define a union. 2. When a variable is associated with a structure, the compiler allocates the memory for each member. The size of structure is greater than or equal to the sum ofsizes of its members. The smaller members may end with unused slack bytes. 2. When a variable is associated with a union, thecompiler allocates thememory by considering the size of the largest memory. So, size of union is equal to the size of largest member. 3. Each member within a structure is assigned unique storage area of location. 3. Memory allocated is shared by individual members of union. 4. The address of each member will be in ascending order This indicates that memory for each member will start at different offset v…

Difference between Linear search and Binary Search in c language

SQL Video Channel : Download all SQL Video



Binary Search Linear Search Works only on sorted items. such as  1,2,3,4,5,6  etc
Works on sorted as well as unsorted items. 12,4,5,3,2,1 etc Very efficient if the items are sorted Very efficient if the items are less and present in the beginning of the list. such as Suppose your list items are : 12,3,4,5,1 and you want to search 12 number then you get beginning in the list. Works well with arrays and not on linked lists. Works with arrays and linked lists.
Number of comparisons are less More number of comparisons are required if the items are present in the later part of the array or its elements are more.

Memory representation of Linked List Data Structures in C Language

Memory representation of Linked List

             In memory the linked list is stored in scattered cells (locations).The memory for each node is allocated dynamically means as and when required. So the Linked List can increase as per the user wish and the size is not fixed, it can vary.

               Suppose first node of linked list is allocated with an address 1008. Its graphical representation looks like the figure shown below:


      Suppose next node is allocated at an address 506, so the list becomes,



  Suppose next node is allocated with an address with an address 10,s the list become,


The other way to represent the linked list is as shown below:




 In the above representation the data stored in the linked list is “INDIA”, the information part of each node contains one character. The external pointer root points to first node’s address 1005. The link part of the node containing information I contains 1007, the address of next node. The last node …