Saturday, 31 August 2013

Opening a File | C Programming Language Tutorial



Opening a File:

C communicates with files using a new data type called a file pointer. This type is defined within stdio. h, and written as FILE *. A file pointer called output_file is declared in a statement like  FILE *output_file;
If we want to store data in a file into the secondary memory, we must specify certain things about the file to the operating system. They include the filename, data structure, purpose.
The general format of the function used for opening a file is 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 pointer 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 the file. The mode does this job.
r     open the file for read only.
w    open the file for writing only.
a     open the file for appending data to it.
r+   open an existing file for update (reading and writing)
w+  create a new file for update. If it already exists, it will be overwritten.
a+   open for append; open for update at the end of the file

Consider the following statements:
FILE *pl, *p2;
pI =fopen("data" ,"r");
p2=fopen("results", "w");

In these statements the pI and p2 are created and assigned to open the files data and results respectively the file data is opened for reading and result is opened for writing. In case the results file already exists, its contents are deleted and the files are opened as a new file. If the data file does not exist error will occur.


0 comments:

Post a Comment

 

C Programming Language Interview Questions and Answers Tutorial for beginners. Copyright 2013 All Rights Reserved