ifstream
(input file stream)ofstream
(output file stream)
#include// standard librark package for files #include "filelib.h' //contains helpful methods
string promptUserForFile(ifstream& stream, string prompt);Asks the user for the name of a file (using the string prompt). The file is opened using the reference parameter stream, and the function returns the name of the file. If the requested file cannot be opened, the user is given additional chances to enter a valid file.
ifstream infile; promptUserForFile(infile, "File?"); char ch; while (infile.get(ch)) { //do something with ch cout << ch << endl; } infile.close();Summary for every file-reading program: (1) Creates
ifstream
object; (2) closes ifstream
object.
ifstream infile; infile.open("File.txt"); char ch; while (infile.get(ch)) { //do something with ch cout << ch << endl; } infile.close();
ch
); (2) while loop continues until read fails. Every iteration of while loop is a new char.ifstream infile; infile.open("File.txt"); string line; while (getline(infile, line)) { //do something with line cout << line << endl; } infile.close();Now reads each line (breaks on newline characters). Still declare the line before the while loop. Still continues until
getline
fails; each while loop iteration has a different line. Notice lowercase l
of getline
(different from Stanford library's getLine
).
ifstream infile; promptUserForFile(infile, "File?"); string word; while (infile >> word) { //do something word } infile.close();Now reads each word (removes whitespace). Still declare the variable before the while loop in which the word will be stored. Stll continues until fails to read a new word. Each while loop iteration has a different word. Works with other types (e.g., int or Vector) too. Do not try to mix with
getline
(recall previous discussion).
Writing output
ofstream
ofstream ofile; promptUserForFile(outfile, "File?"); string word = "Output"; int x = 3; outfile << word << " " << x << endl; outfile.close();Similar to reading formatted input. Works a lot like
cout
. Works with (almost) any type. Use ofstream
instead of ifstream
and <<
instead of >>
.