* File I/O * cout and cin are variables of type ostream and istream respectively * you can create your own variables of type ostream and istream that get output and input from different sources, in this case, files. * MS Word reads from and saves to files. #include int main() { ifstream is; ofstream os; int first, second, third; is.open("in.txt"); os.open("out.txt"); is >> first >> second >> third; os << "The sum is: " << (first + second + third); return 0; } * When you write to a file that you open, if it is not there, it will be created. If it is there, its contents will be deleted before anything is written to it. What if you want to append to the file? os.open("out.txt", ios::app); * Now, if the file exists, written stuff will be added to the end of the file. * What if the file you want to read from does not exist? Or you don't have permission to read from it? Or you open a file for writing and you don't have write permissions? You need to check and make sure your file opened successfully before you do anything with it. is.open("in.txt"); if(is.fail()) { cout << "Opening file in.txt failed." << endl; exit(1); } * We also want to close a file when we're done using it. That way, other programs can access open it. is.close(); * What if you don't know how big the file is? You just want to keep reading in until you hit the end of the file. #include #include int main() { ifstream is; char c; is.open("in.txt"); is >> c; while(!is.eof()) { cout << c; is >> c; } cout << endl; is.close(); return 0; } #include #include #include int main() { ifstream is("in.txt"); if(is.fail()) { cout << "Input file in.txt failed to open." << endl; exit(1); } ofstream os("out.txt"); if(os.fail()) { cout << "Output file out.txt failed to open." << endl; exit(1); } int sum = 0; int n; is >> n; while(!is.eof()) { sum += n; is >> n; } os >> "The sum is: " << sum; is.close(); os.close(); return 0; } * What if we wanted to write a program that copies from one file to another? We want the file names to be inputted on the command line. #include #include #include int main(int argc, char *argv[]) { if(argc != 3) { cout << "Usage: cp input-file output-file" << endl; exit(1); } ifstream is(argv[1]); if(is.fail()) { cout << "Input file " << argv[1] << " failed to open." << endl; exit(1); } ofstream os(argv[2]); if(os.fail()) { cout << "Output file " << argv[2] << " failed to open." << endl; exit(1); } char c; is >> c; while(!is.eof()) { os << c; is >> c; } is.close(); os.close(); return 0; }