Skip to main content

Posts

Showing posts with the label tellg()

Short notes on 1. Namespaces 2. Exception handling 3. Basic functions of seekg(), seekp(), tellg(), tellp()

1. Namespaces: Namespaces are a feature in C++ that allow us to group related functions, classes, and variables under a single name. This helps in preventing naming conflicts and organizing code. We can create a namespace using the keyword "namespace" followed by the namespace name and enclosing the contents within curly braces. We can access the contents of a namespace using the scope resolution operator "::". For example: namespace myNamespace {    int myFunction() {       // function code    } } int main() {    myNamespace::myFunction(); // accessing function from the namespace    return 0; } 2. Exception handling: Exception handling is a mechanism in C++ that allows us to handle errors and unexpected events that occur during program execution. We can use the keywords "try", "catch" and "throw" to implement exception handling. We enclose the code that can generate an exception within the try block. If an exception is thrown, the ...

Explain the role of seekg(), seekp(), tellg(), and tellp() functions in the process of random access in a binary file. How can we open a text file and read from it.

 In C++, seekg(), seekp(), tellg(), and tellp() are functions that allow us to perform random access on a binary file. seekg() and seekp() are used to set the position of the read/write pointer in a file. seekg() sets the position of the input file pointer (ifstream), while seekp() sets the position of the output file pointer (ofstream). These functions take an offset value and a seek direction as parameters. The seek direction can be one of three values: ios::beg (beginning of the file) ios::cur (current position of the pointer) ios::end (end of the file) For example, to set the input file pointer to the 10th byte from the beginning of the file, we can use: ifstream infile("example.bin", ios::binary); infile.seekg(10, ios::beg); tellg() and tellp() are used to get the current position of the input and output file pointers, respectively. These functions take no parameters and return the current position of the file pointer. For example, to get the current position of the outp...