Lab P20 β Perform random file access.
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
ABZDEExplanation
- seekp(2) writes Z at index 2.
- Reads all chars.
Viva / Important Questions
Short Questions
- What is random access?
- seekg vs seekp?
Long Questions
- Explain the program in detail.
- 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.