Lab P20 β€” Perform random file access.

NBC351 Β· Program 20⏱ 8 min read❓ 5 MCQs

Aim

Aim: Demonstrate random file access using seekg/seekp.

Theory

Demonstrate random file access using seekg/seekp.

C++ Program

#include 
#include 
using namespace std;
int main(){
    fstream f("rand.txt",ios::out); f<<"ABCDE"; f.close();
    f.open("rand.txt",ios::in|ios::out);
    f.seekp(2); f<<"Z";          // write at pos 2
    f.seekg(0); char c;
    while(f.get(c)) cout<

Expected Output

ABZDE

Explanation

  • seekp(2) writes Z at index 2.
  • Reads all chars.

Viva / Important Questions

Short Questions

  1. What is random access?
  2. seekg vs seekp?

Long Questions

  1. Explain the program in detail.
  2. Discuss key concepts demonstrated.

MCQ Practice

1. Random access allows:

  • Jump to any position
  • Only sequential
  • Only read
  • None
Answer: Jump to any position.

2. seekg moves:

  • Read pointer
  • Write pointer
  • Both
  • None
Answer: Read pointer.

3. seekp moves:

  • Write pointer
  • Read pointer
  • Both
  • None
Answer: Write pointer.

4. tellg returns:

  • Read position
  • Write position
  • Size
  • None
Answer: Read position.

5. Random access useful for:

  • Records/databases
  • Streaming
  • Logging
  • None
Answer: Records/databases.

Quick Revision

  • Random access via seek.
  • seekg read, seekp write.