fstream
library
ofstream
class
ofstream fout; // Create a new file fout.open("test.txt"); // Send output to the file fout << "This is a test." << endl; // Flush the output buffer fout.close();would produce a file called
test.txt
(in the same directory as your .cpp
file)
that contains:
This is a test.
open("filename")
- creates a new file if it
doesn't exist or erases contents of previously existing file
fout <<
- send output to the
file instead of to the console (cout
)
close()
- flush the output buffer (output buffer might
contain data that has not been written to the file yet)
ios::app
flag when openning to append to a file
test.txt
ofstream fout; fout.open("test.txt", ios::app); fout << "This line will be appended to the end of the file."; fout.close();would produce:
This is a test. This line will be appended to the end of the file.
string input_filename, output_filename, line; cout << "Input filename? "; getline(cin, input_filename); output_filename = "Copy - " + input_filename; ifstream fin; fin.open(input_filename); ofstream fout; fout.open(output_filename); // Read each line from the input file and send it to // the output file getline(fin, line); while (fin.good()) { fout << line << endl; getline(fin, line); } fin.close(); fout.close(); cout << "Copied the file to " << output_filename;Running the program:
Input filename? nums.txt Copied the file to Copy - nums.txt
fail()
to fix this
fail()
to
see if the file exists or not
ofstream
and ifstream
objects may be passed to
functions as parameters
// Must pass streams by reference! int ReadNumber(ifstream &fin) { int num; fin >> num; return num; } void main() { ifstream fin; fin.open("somefile.txt"); // Display number from somefile.txt cout << ReadNumber(fin); fin.close(); }