In C++, files are mainly dealt by using three classes fstream, ifstream, ofstream available in fstream headerfile.
ofstream: Stream class to write on files
ifstream: Stream class to read from files
fstream: Stream class to both read and write from/to files.
Now the first step to open the particular file for read or write operation. We can open file by
1. passing file name in constructor at the time of object creation
2. using the open method
Open File by using constructor
ifstream (const char* filename, ios_base::openmode mode = ios_base::in);
ifstream fin(filename, openmode) by default openmode = ios::in
Open File by using open method
Calling of default constructor
|Member Constant||Stands For||Access|
|in *||input||File open for reading: the internal stream buffer supports input operations.|
|out||output||File open for writing: the internal stream buffer supports output operations.|
|binary||binary||Operations are performed in binary mode rather than text.|
|ate||at end||The output position starts at the end of the file.|
|app||append||All output operations happen at the end of the file, appending to its existing contents.|
|trunc||truncate||Any contents that existed in the file before it is open are discarded.|
Default Open Modes :
|fstream||ios::in | ios::out|
Problem Statement : To read and write a File in C++.
Input : Welcome in GeeksforGeeks. Best way to learn things. -1 Output : Welcome in GeeksforGeeks. Best way to learn things.
Below is the implementation by using ifsream & ofstream classes.
Below is the implementation by using fstream class.
- tellp() in file handling with c++ with example
- Four File Handling Hacks which every C/C++ Programmer should know
- Set position with seekg() in C++ language file handling
- C program to copy contents of one file to another file
- C++ | Signal Handling
- Exception Handling in C++
- Comparison of Exception Handling in C++ and Java
- Exception handling and object destruction | Set 1
- Anonymous classes in C++
- Trivial classes in C++
- Nested Classes in C++
- Local Classes in C++
- C++ Classes and Objects
- Virtual functions in derived classes
- Socket Programming in C/C++: Handling multiple clients on server without multi threading