C++ File Handling Concepts and Examples
1. How are file streams used in C++?
File streams are used to perform input/output operations on files.
C++ uses three main classes from the <fstream> library:
- ifstream - for reading from files.
- ofstream - for writing to files.
- fstream - for both reading and writing.
Example:
#include <fstream>
std::ofstream fout("file.txt"); // output stream
std::ifstream fin("file.txt"); // input stream
2. What are file pointers and how can they be manipulated?
File pointers track the current position in a file.
- get pointer (seekg): for reading.
- put pointer (seekp): for writing.
Functions:
- seekg(offset, direction)
- seekp(offset, direction)
- tellg()
- tellp()
Directions:
- ios::beg - beginning of file
- ios::cur - current position
- ios::end - end of file
3. Explain sequential vs. random file access.
Sequential Access:
- Data accessed in order.
- Slower for large files.
Random Access:
- Any byte can be accessed directly.
1. How are file streams used in C++?
File streams are used to perform input/output operations on files.
C++ uses three main classes from the <fstream> library:
- ifstream - for reading from files.
- ofstream - for writing to files.
- fstream - for both reading and writing.
Example:
#include <fstream>
std::ofstream fout("file.txt"); // output stream
std::ifstream fin("file.txt"); // input stream
2. What are file pointers and how can they be manipulated?
File pointers track the current position in a file.
- get pointer (seekg): for reading.
- put pointer (seekp): for writing.
Functions:
- seekg(offset, direction)
- seekp(offset, direction)
- tellg()
- tellp()
Directions:
- ios::beg - beginning of file
- ios::cur - current position
- ios::end - end of file
3. Explain sequential vs. random file access.
Sequential Access:
- Data accessed in order.
- Slower for large files.
Random Access:
- Any byte can be accessed directly.