Which of the following file stream function will not move the file pointer to…
2022
Which of the following file stream function will not move the file pointer to the (N+1)th record of a binary file F created with the help of objects of class EMPLOYEE?
- A.
F.seekp(N * sizeof(EMPLOYEE));
- B.
F.seekg(F.tellg() * N);
- C.
F.seekg(sizeof(EMPLOYEE) * N);
- D.
POS = sizeof(EMPLOYEE) * N;
Attempted by 127 students.
Show answer & explanation
Correct answer: B
Answer: F.seekg(F.tellg() * N);
Key insight: To position the file pointer at the (N+1)th record in a binary file of contiguous records, the required byte offset from the file start is N * sizeof(EMPLOYEE).
F.seekp(N * sizeof(EMPLOYEE)); — Correct for writing: seekp repositions the put (write) pointer to the offset N * sizeof(EMPLOYEE), accessing the (N+1)th record for writes.
F.seekg(F.tellg() * N); — Incorrect: tellg() returns the current get position; multiplying that by N does not compute the desired offset. This will not reliably place the pointer at the (N+1)th record.
F.seekg(sizeof(EMPLOYEE) * N); — Correct for reading: seekg repositions the get (read) pointer to the offset N * sizeof(EMPLOYEE), accessing the (N+1)th record for reads.
POS = sizeof(EMPLOYEE) * N; — Not a file-stream operation: this merely assigns a value to a variable and does not move any file pointer. To use this offset you must call a seek function, e.g. F.seekg(POS) or F.seekp(POS).
Summary: The expression that will not move the file pointer to the (N+1)th record is F.seekg(F.tellg() * N); because it computes the wrong offset. Also note that a plain assignment like POS = sizeof(EMPLOYEE) * N; does not move the pointer by itself — you must pass that offset to seekg/seekp.