How to Open a File in C
if we want to store data in the secondary memory, we must
specify certain things about the file, to the operating system. They include:
1. Filename
2. Data
structure
3. Purpose
Filename is a
string of characters that make up a valid filename for the operating system. It
may contain two parts, a primary name and an optional period with the
extension. Examples are:
Input.data
store
student.c
Text.out
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 a 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 operating
a file:
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 file name and assigns an identifier to the FILE type pointer fp.
The second statement also specifies the purpose of opening
this file. The mode does this job. Mode can be one of the following:
r -- > open
the file for reading only
w -- >
open the file for writing only
a -- >
open the file for appending ( or adding ) data to it
For Example:
File *p1, *p2 ;
p1 = fopen (“data”, “r”);
p2 = fopen (“results”, “w”);
Post a Comment