Files: Opening and Closing File Using Open, Open Function and File Pointers

Get top class preparation for competitive exams right from your home: get questions, notes, tests, video lectures and more- for all subjects of your exam.

Opening & Closing File Using Open ()

Open () Function

The open () function has two parameters: filename and access mode. The general format is:

Stream _object. open ( “filename” , access mode) .

The second argument specifies the mode in which the file is opened. The default values are taken for if stream or of stream functions. (The mode is not defined explicitly) .

ios: in for if stream functions

ios: out for of stream functions

The file mode parameters can take one or more of the constants defined in the class ios. The following table shows the file mode parameters.

The Following Table Shows the File Mode Parameters
ParameterMeaning
ios: appIt opens the file in output mode. The file pointer is at the end of file and it can add a record.
ios: ateThe file pointer is at the end of the file and it allows to add data or to modify the existing data anywhere in the file.
ios: binaryBinary file
ios: inIt opens the file in input mode. The file pointer is at the top of the file and it is ready for reading.
ios: no createIf file is already present, it opens the file otherwise open fails.
ios: no replaceIf file is not present, it opens the file otherwise open statement fails.
ios: outIt opens the file in output mode. The file pointer is at the end of the file. If it already has a data, the output mode erases the content of the file.
ios: trunkIt deletes the contents of the file if exist

The mode can combine two or more parameters using bitwise OR operator.

Example:

Out file. open ( “ABC” , ios:: in l ios:: out l ios:: binary) ;

File Pointers

File has two associated pointers called input pointer (or get pointer) and output pointer (or put pointer) .

Each time an input or output operation takes place, the pointer moves automatically. There are two pointers.

See kg () It moves get pointer to a specified location.

See kp () It moves the put pointer to a specified location.

A file can be viewed as

Pointer to a Specified Location

ios: beg means start of the file

ios: cur means current position of the pointer

ios: end means end of the file.

The see kg () and see kp () statement has two parameters.

Object. See kg (no. of bytes, reposition) .

Object. See kp (no. of bytes, reposition) .

The reposition takes one of the above three constants defined in the ios class.

Example 1

In file. See kg (0, ios: beg) .

It moves the pointer to the beginning of the file. In this case, the reposition ios: beg is optional.

In file. see kg (100, ios: cur) ; It moves the pointer 100 bytes forward from the current position.

In file. See kg (-200, ios: end) .

It moves the pointer 200 bytes backward from the end of the file.