Professional Documents
Culture Documents
Chapter 8 -
File I/O Similar to writing to screen
Use object connected to output file
Need the fstream header
#include <fstream>
Open file for writing
Declare object of ofstream class
1 2
General form
General form
ofstream object_name (“file_name”);
object_name << variable_name;
Choose object_name like variable name
Use ofstream object to write to file like
object_name is object of class ofstream
cout was used
Filename is where output will be stored
ofstream outfile(“C:\\salary.out”);
Can use full pathname “C:\\salary.out ”
outfile << “Salary for week was ” << money;
3 4
Example 1 Example 2
//Appending a file - using the ios::app mode to append a file
//Creating and writing to a file
#include <fstream> #include <fstream>
using namespace std; #include <string>
int main() #include <iostream>
{ using namespace std;
ofstream SaveFile("cpp-home.txt"); //a file is created int main()
//ofstream SaveFile; {
string str = "\This is the appending part";
//SaveFile.open ("cpp-home.txt");
ofstream myFile("cpp-home.txt ", ios::app);
SaveFile << "Hello World!"; //the file is written myFile << str <<endl;
SaveFile.close(); //the file is closed myFile.close();
return 0; return 0;
} }
5 6
Exercise 1 Exercise 1
Create a text file with the following requirement: #include <fstream>
#include <string>
#include <iostream>
1. The file name will be defined by the user. using namespace std;
2. The file should be in “append” mode int main()
{
string file; //char file[20];
With the file created, write your name to the file. cin >> file;
ofstream SaveFile(file.c_str(), ios::app); //ofstream SaveFile(file , ios::app);
7 8
1/2
Closing Files (input and output) Open File for Reading
9 10
11 12
Example 3
Example 4 – Display the file contents
15 16
2/2