![]() ![]() | ||||
![]() ![]() |
Lesson 10: C++ File
I/O (Printable
Version) #include <fstream.h> #include <iostream.h> int main() { char str[10]; //Used later ofstream a_file("example.txt"); //Creates an instance of ofstream, and opens example.txt a_file<<"This text will now be inside of example.txt"; //Outputs to example.txt through a_file a_file.close(); //Closes up the file ifstream b_file("example.txt"); //Opens for reading the file b_file>>str; //Reads one string from the file cout<<str; //Should output 'this' b_file.close(); //Do not forget this! }The default mode for opening a file with ofstream's constructor is to create it if it does not exist, or delete everything in it if something does exist in it. If necessary, you can give a second argument that specifies how the file should be handled. They are listed below: ios::app -- Opens the file, and allows additions at the end ios::ate -- Opens the file, but allows additions anywhere ios::trunc -- Deletes everything in the file ios::nocreate -- Does not open if the file must be created ios::noreplace -- Does not open if the file already exists For example: ofstream a_file("test.txt", ios::nocreate);The above code will only open the file test.txt if that file already exists. Quiz yourself Previous: Strings Next: Typecasting ----- |
| ||
|