Interview Questions
File Handling (fstream) · Study material
C++ File Handling – Interview Questions
1. Which classes are used for file handling in C++?
std::ifstream (read), std::ofstream (write) and std::fstream (both), from <fstream>.
2. How do you check whether a file opened successfully?
if (!file) or if (!file.is_open()) right after opening.
3. What is the default mode of ofstream?
std::ios::out | std::ios::trunc – existing contents are discarded.
4. How do you append to a file?
Open with std::ios::app: std::ofstream f("log.txt", std::ios::app);
5. app vs ate?
app forces every write to the end; ate only starts at the end, and the position can be moved later.
6. Why is while (!file.eof()) wrong?
eof becomes true only after a read fails, so the loop processes one invalid item; and if a read fails for another reason, eof never becomes true.
7. getline vs >>?
getline reads a whole line including spaces; >> reads one whitespace-separated token and leaves the newline.
8. What do good(), eof(), fail() and bad() mean?
No error; end of file reached; an operation failed; a serious I/O error.
9. What does clear() do?
Resets the stream's error flags so further operations can work.
10. What are seekg and tellg?
seekg moves the read position; tellg returns it. seekp/tellp do the same for writing.
11. How do you write binary data?
Open with std::ios::binary and use write(reinterpret_cast<const char*>(&obj), sizeof obj) – only for trivially copyable types.
12. Why not write a std::string with write()?
Its bytes contain a pointer to heap memory (or an implementation-specific small buffer), not the text itself.
13. Is it necessary to call close()?
No; the destructor closes the file. close() is useful to release it early or check for errors.
14. What is stringstream used for?
Parsing and building strings with stream syntax, e.g. splitting a CSV line or formatting values.
15. How do you read a file in reverse or jump to a record?
Use seekg with an offset (std::ios::end for relative to the end) – easiest with fixed-size binary records.
16. What does std::filesystem provide?
Paths, existence and size checks, directory creation and iteration, copy, rename and remove (C++17).
17. How do you get a file's size?
std::filesystem::file_size(path), or seekg(0, std::ios::end) then tellg().
18. How can a stream report errors with exceptions?
stream.exceptions(std::ios::failbit | std::ios::badbit); failures then throw std::ios_base::failure.
19. What happens when you open a non-existent file with ifstream?
Opening fails: failbit is set and nothing is created.
20. How do you update part of an existing file without truncating it?
Open an fstream with std::ios::in | std::ios::out, seekp to the position and write.