Sunday, 21 January 2018

Defining And Opening A File


Defining And Opening A File


 If we want to store data in a file in the secondary memory, we must specify certain things about the file , to the operating system. They include:

 1.File name.
 2.Data Structure.
 3.Purpose.
 File name is a string of characters that make up valid filename for the operating system. It may contain two parts ,a primary name and an operational period with the extension.Data structure of a file is defined as FILE in the library of standard I/O function definitions. Therefore , all files 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. Following is  the general format for declaring and opening a file:



FILE *fp;
fp=fopen("filename","mode");


 The first statement declares the variable fp as a "pointer to the data type FILE". As stated earlier,
FILE is a structure that is defined in the I/O library.The second statement opens the file named filename and assigns an identifier to the FILE type fp .This pointer which contains all the information about the file is subsequently  used as a communication link between the system and the program.
 The second statement also specifies the purpose of opening this file .The Mode does the job. Mode can be one of the following:

Mode Type Operation
"r" Searches File . If the file exists loads it into memory and sets up a pointer which points to the first character in it , if file doesn’t exists it returns null. Operations possible – Reading from a file.
"w" Searches File . If the file exists its contents are overwritten .If file doesn’t exists new file is created .Returns null if unable to open a file. Operations possible – Writing to a file.
"a" Searches File . If the file exists loads it into memory and sets up a pointer to point the first character .If file doesn’t exists new file is created .Returns null if unable to open a file. Operations possible – Appending new contents at the end of file.
"r+" Searches File .If it exists,loads it into memory sets up a pointer which points to the first character in it. If does not exist it returns NULL. Operations possible – reading,writing,modifying existing contents.
"w+" Searches File . If the file exists its contents are destroyed .If file doesn’t exists new file is created .Returns null if unable to open a file.
"a+" Searches File . If the file exists loads in to memory and sets up a pointer which points to first of a file. If file doesn’t exists new file is created .Returns null if unable to open a file. Operations possible – Writing to a file.

0 comments:

Post a Comment