C++ File Streams
C++ uses stream classes to perform file operations. Two primary header files <fstream> for file stream and <iostream> for standard I/O streams are used to handle files.
Opening Files
To open files, create an object of ifstream or ofstream, then use the open() method. Modes like ios::in and ios::out specify the file access mode.
Reading Files
Use the getline() function or stream operator (>>) to read from files. getline() reads a string until a newline is encountered. The stream operator reads formatted data.
Writing to Files
ofstream is used to write to files. Use the insertion operator (<<) to output data. It can write strings, numbers, and other data types.
Binary vs Text
C++ can handle binary and text files. ios::binary flag is used for reading/writing in binary mode. Binary files are compact and faster for I/O operations.
Buffer Manipulation
Manipulating the I/O buffer can optimize file operations. Functions like flush() clear the buffer, and seekg()/seekp() move the read/write pointer within the file.
Error Handling
Check for file I/O errors using fail(), bad(), eof(), and good(). These methods help identify issues like bad reads, write fails, and end of file conditions.