Friday, 22 September 2017

File Open close

Q : How to create a file in C? Why should a user close the file?

Answer : 


For create a file in language,stdio.h header file has fopen method which takes two arguments and return base address of opening file.

Suntax

Return_address  fopen(“file name”,”Open mode”);

Open mode indicate file opening option whether a file is open for read, write, append or both.


If file is successfully open then base address of file returned otherwise NULL returned to indicate unsuccessful of file opening. Following demonstrate how you can open a file.


File Mode
Meaning of Mode
During Inexistence of file
r
Open for reading.
If the file does not exist, fopen() returns NULL.
rb
Open for reading in binary mode.
If the file does not exist, fopen() returns NULL.
w
Open for writing.
If the file exists, its contents are overwritten. If the file does not exist, it will be created.
wb
Open for writing in binary mode.
If the file exists, its contents are overwritten. If the file does not exist, it will be created.
a
Open for append. i.e, Data is added to end of file.
If the file does not exists, it will be created.
ab
Open for append in binary mode. i.e, Data is added to end of file.
If the file does not exists, it will be created.
r+
Open for both reading and writing.
If the file does not exist, fopen() returns NULL.
rb+
Open for both reading and writing in binary mode.
If the file does not exist, fopen() returns NULL.
w+
Open for both reading and writing.
If the file exists, its contents are overwritten. If the file does not exist, it will be created.
wb+
Open for both reading and writing in binary mode.
If the file exists, its contents are overwritten. If the file does not exist, it will be created.
a+
Open for both reading and appending.
If the file does not exists, it will be created.
ab+
Open for both reading and appending in binary mode.
If the file does not exists, it will be created.


#include<stdio.h>

void main()
{
     FILE *pt;
     pt=fopen("test.txt","r");
     if(pt==NULL)
          printf("\nFile Opening Error");
     else
          printf("\nFile open successfully");
     fclose(pt);

}

When a file is opened and after apply read/ write operation it need to close properly for following reason
  • To save data which has been changed?
  • Release buffer
  • Release resource of computer
  • Fclose function is use to close a file .


Fclose(pt);

No comments:

Post a Comment