Opening and Closing Files
Opening files: fopen( )
- fopen() is a predefined file handling function that is used to open an already existing file or to create a file.
- It accepts two strings, the first is the filename, and the second is the mode in which it has to be opened.
The general format of the function used for opening a file is as follows:
Syntax:
FILE *filepointer; filepointer=fopen(“filename.filetype”,”mode”);
Example:
FILE *fp; fp= fopen(“gitam.txt”,”w”); where gitam.txt is file name. where ‘w’ is write mode.
Note: The function fopen( ) is compulsory for the files to do any operations, without fopen( ) we cannot perform operations on files.

Where will be file saved in the computer?
1. A) If you didn’t mention the path, by default the file will be saved in the TC folder meant in the drive where C-Lang is installed.
Example:
fp=fopen(“hello.txt”, “w”);
1. B) If you mention the path in fopen( ) function, then the new file will be saved in that particular path.Path should be mentioned as follows:
Example:
fp=fopen(“d:\\gitam\\hello.txt”, “w”); (Or) fp=fopen(“d:/gitam/hello.txt”, “w”);
Closing the File: fclose( fp)
- Once we have finished reading the file, we must close it.This is done using the function fclose through the statement, fclose( fp );
- When writing to a file, the data is written is not put on the drive immediately.It is stored in a buffer. When the buffer is full, all its content is recorded on the disk. The process of emptying the buffer by writing its contents to the disk is referred to as purging the buffer.
- Closing the file clears the buffer and frees the space taken by the FILE structure that is returned by fopen. Operating System normally imposes a limit on the number of files that can be opened by a process at a time. Hence, closing a file means that another can be opened in its place Hence, closing one file means that another can be opened in its place. Therefore, if a specific FILE pointer is not required after a certain point in a program, go to fclose and close the file.
Syntax:
fclose(filepointer);
Example:
fclose(fp); // where fp is a file pointer.