Programming Pandit

c/c++/c#/Javav/Python


Latest Update

Sunday, November 17, 2024

File Pointers and their Manipulations

 

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

  1. Input File Pointer (get pointer)
    Used for reading from a file. It determines where the next data will be read.

  2. 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:

FunctionPurpose
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::begBeginning of the file (used with seekg or seekp).
ios::curCurrent position in the file (used with seekg or seekp).
ios::endEnd 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.

Syntax:
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.

    Syntax:
    file.seekp(offset, direction);

    3. Getting the Current Pointer Position

    • tellg() gives the current position of the get pointer.
    • tellp() gives the current position of the put pointer.

      Example: File Pointer Manipulation

    #include <iostream>
    #include <fstream>
    using namespace std;

    int main() {
        fstream file;

        // Open a file in read/write mode
        file.open("example.txt", ios::in | ios::out | ios::trunc);

        if (!file) {
            cout << "Error opening file!" << endl;
            return 1;
        }

        // Write some data to the file
        file << "ABCDEFGH";

        // Move the put pointer to the beginning
        file.seekp(0, ios::beg);

        // Overwrite the first character
        file << 'Z';

        // Move the get pointer to the 4th character
        file.seekg(3, ios::beg);

        // Read the 4th character
        char ch;
        file.get(ch);
        cout << "Character at 4th position: " << ch << endl;

        // Display the current positions of get and put pointers
        cout << "Get pointer position: " << file.tellg() << endl;
        cout << "Put pointer position: " << file.tellp() << endl;

        file.close();
        return 0;
    }

    Example: 




    Key Points

    1. Default Behavior of Pointers:

      • When a file is opened in read mode, the get pointer is set to the beginning of the file.
      • When a file is opened in write mode, the put pointer is set to the beginning (or the end if in append mode).
    2. Using seekg and seekp:

      • seekg is used for positioning the input pointer (reading).
      • seekp is used for positioning the output pointer (writing).
    3. Offsets and Directions:
      The offset parameter specifies the number of bytes to move. The direction specifies the starting point:

      • ios::beg: Beginning of the file.
      • ios::cur: Current position in the file.
      • ios::end: End of the file.


    Example: Random Access with File Pointers

    Random access is achieved by directly moving the file pointers to the required position.

    #include <iostream>
    #include <fstream>
    using namespace std;

    int main() {
        fstream file("data.bin", ios::out | ios::in | ios::binary | ios::trunc);

        if (!file) {
            cout << "Error opening file!" << endl;
            return 1;
        }

        // Write integers to the binary file
        for (int i = 1; i <= 5; i++) {
            file.write((char*)&i, sizeof(i));
        }

        // Move to the 3rd integer (2nd index, as indexing starts from 0)
        file.seekg(2 * sizeof(int), ios::beg);

        // Read and display the 3rd integer
        int num;
        file.read((char*)&num, sizeof(num));
        cout << "The 3rd integer is: " << num << endl;

        // Update the 3rd integer to 10
        num = 10;
        file.seekp(2 * sizeof(int), ios::beg);
        file.write((char*)&num, sizeof(num));

        // Verify the update
        file.seekg(0, ios::beg); // Reset to beginning
        cout << "Updated file contents:" << endl;
        while (file.read((char*)&num, sizeof(num))) {
            cout << num << " ";
        }
        cout << endl;

        file.close();
        return 0;
    }






    Summary

    • File pointers provide flexibility to read/write from specific positions in a file.
    • Use seekg and seekp for moving file pointers and tellg/tellp to get their positions.
    • These functions are vital for random access in large files, enabling efficient data management.


    No comments:

    Post a Comment