Showing posts with label Opening and closing a file. Show all posts
Showing posts with label Opening and closing a file. Show all posts

Friday 30 March 2012

Opening and closing a file (fopen(), fclose())


Opening a file (fopen())

To read and write information from file and to file respectively file must be opened. Opening a file establishes a link between the program and operating system. fopen() function is used to create a new file for use or opens a new existing file for use.
Syntax:

          FILE *fp
          fp= fopen (“Filename”, “mode”);

Here,

è    The first statement declares the variable fp as a “pointer to the data type FILE” . FILE is the structure that is defined in the I/O library. fp is a pointer variable , which contains address of FILE.
è    Fopen takes two argument. First argument filename is a name of file and it needs a complete path.
è    The second argument is a file opening mode. It indicates the purpose of opening file.There are several modes available with fopen(). They are listed as follow:

 File mode
Description
“r”   
Opening the file for reading.

“a”
Opening the file for appending.

“w”  
Opening the file for writing.

“w+”
open for the writing and reading (existing file will be overwritten).
“r+”
open for the reading and updating (file must already exist).
“a+”
open for the appending and reading (file may or may not exist).
rb
Opens an existing binary file for reading.
wb
Creates a binary file for writing.

ab
Opens an existing binary file for appending.

è    Both the argument file name and mode are specified as a string . They should be enclosed in double quotation mark.
è    This function returns the required file pointer. The value NULL will be returned, if the file cannot be opened for any reason.
Ex,
FILE *fp1;
fp1 = fopen(“book.txt”, “r”);

As shown in above example file named  book.txt will open for reading purpose. If this file does not exists , an error will occur.

Ex,
FILE *fp2;
fp2 = fopen(“mark.txt”, “w”);

As shown in above example file named mark.txt opened for writing purpose. If this file is already exists , its contents are deleted and file is opened as new file.

Closing a file (fclose())

When finish the work of file, it must be closed. It makes sure that all the information related with the file is flushed out from the buffer and all links to the file are broken and also restrict the misuse of file. fclose() function is used to close a file.
Syntax:

fclose(File_ptr);

Here, only one argument is the file pointer which is pointer to FILE structure.
If file is closed successfully then it returns 0 or constant value EOF (End Of File) if any error occurred.
Ex,
     fclose(fp1);

As shown in given example, the file pointing to fp1 will close.


Posted By : Ruchita Pandya