File Pointers and Their Manipulations in C++
In C++, file pointers are used to manage the position of the reading or writing cursor within a file. These pointers allow precise control over where data is read from or written to, making file handling efficient and flexible.
Types of File Pointers
Input File Pointer (
get pointer)
Used for reading from a file. It determines where the next data will be read.Output File Pointer (
put pointer)
Used for writing to a file. It determines where the next data will be written.
File Pointer Manipulation Functions
C++ provides several member functions for manipulating file pointers. These are:
| Function | Purpose |
|---|---|
seekg(offset, dir) | Moves the get pointer (read) to a specific location in the file. |
seekp(offset, dir) | Moves the put pointer (write) to a specific location in the file. |
tellg() | Returns the current position of the get pointer. |
tellp() | Returns the current position of the put pointer. |
ios::beg | Beginning of the file (used with seekg or seekp). |
ios::cur | Current position in the file (used with seekg or seekp). |
ios::end | End of the file (used with seekg or seekp). |
How to Manipulate File Pointers
1. Moving the get Pointer
The seekg() function moves the input file pointer to a specific position.
file.seekg(offset, direction);
offset: Number of bytes to move.direction: Position relative to which the movement occurs (ios::beg, ios::cur, or ios::end).2. Moving the put Pointer
The seekp() function moves the output file pointer to a specific position.
file.seekp(offset, direction);
3. Getting the Current Pointer Position
tellg()gives the current position of thegetpointer.tellp()gives the current position of theputpointer.
Example: File Pointer Manipulation
Key Points
Default Behavior of Pointers:
- When a file is opened in read mode, the
get pointeris set to the beginning of the file. - When a file is opened in write mode, the
put pointeris set to the beginning (or the end if in append mode).
- When a file is opened in read mode, the
Using
seekgandseekp:seekgis used for positioning the input pointer (reading).seekpis used for positioning the output pointer (writing).
Offsets and Directions:
Theoffsetparameter specifies the number of bytes to move. Thedirectionspecifies the starting point:ios::beg: Beginning of the file.ios::cur: Current position in the file.ios::end: End of the file.
Summary
- File pointers provide flexibility to read/write from specific positions in a file.
- Use
seekgandseekpfor moving file pointers andtellg/tellpto get their positions. - These functions are vital for random access in large files, enabling efficient data management.
No comments:
Post a Comment