580 likes | 681 Views
Reading & Writing to Files. helloworld.cpp. #include <iostream> using namespace std; int main() { cout << "Hello World!" << endl; cout << "Goodbye World!" << endl; return 0; }. helloworld.cpp. #include <iostream> using namespace std; int main() {
E N D
Reading & Writing to Files The Ohio State University
helloworld.cpp #include <iostream> using namespace std; int main() { cout << "Hello World!" << endl; cout << "Goodbye World!" << endl; return 0; } The Ohio State University
helloworld.cpp #include <iostream> using namespace std; int main() { cout << "Hello World!" << endl; cout << "Goodbye World!" << endl; return 0; } >helloworld.exe Hello World! Goodbye World! > The Ohio State University
Unix: Redirecting Output to a File • On Unix we can redirect output to a file using the ‘>’ symbol: > helloworld.exe > hellofile.txt > The Ohio State University
Writing to Files The Ohio State University
I/O File Streams • A File Stream is a one-way transmission path used to connect a file stored on a physical device (disk, CD-ROM, etc) to a program. • Two directions: • Input File Stream (read from a file) • Output File Stream (write to a file) • To use file stream operations we #include <fstream> The Ohio State University
Writing to Files: Output File Stream • To write a file: • Create an output stream object • Establish connection to a file • Check Validity • Start writing • Close the file The Ohio State University
writeFile1.cpp #include <cstdlib> // function exit() is in cstdlib #include <fstream> // class ofstream() is in fstream #include <iostream> using namespace std; int main() { ofstream fout; // declare an output file stream fout.open("hellofile.txt", ios::out); // open file file_name for output if (!fout.is_open()) // check if file is opened for output { cerr << "Unable to open file hellofile.txt." << endl; exit(10); } The Ohio State University
writeFile1.cpp (cont) cout << "Writing to file hellofile.txt." << endl; // write text to the file fout << "Hello World!" << endl; fout << "Goodbye World!" << endl; // close file stream fout fout.close(); return 0; } The Ohio State University
Writing to Files (1) • “Create an output stream object” • Make sure we included the <fstream> class. • Create a variable of type ofstream. For example, ofstream fout; • The fout variable is what we would also call an “output file handler” The Ohio State University
Writing to Files (2) • “Establish a connection to a file” • Open the file “hellofile.txt” for output: fout.open(“hellofile.txt”, ios::out); The Ohio State University
Writing to Files (3) • “Check Validity” • Many things can prevent our file from being opened. • For instance, we may not have permission to write to hellofile.txt. These runtime errors must be handled before we do any writing! if (!fout.is_open()) // check if file is open { cerr << "Unable to open file hellofile.txt." << endl; exit(10); } The Ohio State University
Writing to Files (3) • “Check Validity” (continued…) • In the previous code, exit() is a function that terminates program execution. • So, why not just use return 0; as we have been all this time to indicate termination of main()? • We could have, but exit() actually performs some routine maintenance before termination (including file stream cleanup). • To use exit() we must first #include <cstdlib> The Ohio State University
Writing to Files (4) • “Start writing” • Now that we are certain our file handler, fout, is valid we can start writing to the file that is associated with it. • This should look familiar... fout << “Hello World” << endl; • This will print “Hello World” to hellofile.txt The Ohio State University
Writing to Files (5) • “Close the file” • After we are finished writing to our file, it is always important to close the file: fout.close(); • Why is this a good idea? • Can now reuse fout handler for other file writes • If we are not careful, our program could be keeping many files open… which can lead to very bad things. The Ohio State University
Formatted Writing to Files • Notice the similarities between cout and fout. • In fact, everything we can do with cout also applies to fout. Including I/O manipulation: setprecision(), setw(), etc. • Though we named our file handler fout to strike name similarities with cout, we could have actually named it anything arbitrary (just like other variables). The Ohio State University
writeFile2.cpp #include <cstdlib> // function exit() is in cstdlib #include <fstream> // class ofstream() is in fstream #include <iomanip> #include <iostream> using namespace std; int main() { ofstream fout; // declare an output file stream fout.open("sample.txt" , ios::out); // open file file_name for output if (!fout.is_open()) // check if file is opened for output { cerr << "Unable to open file sample.txt." << endl; exit(10); } The Ohio State University
writeFile2.cpp (cont) cout << "Writing to file sample.txt." << endl; // write to the file fout << "Test file output." << endl; fout << "100.0/3.0 = " << 100.0/3.0 << endl; fout.precision(12); fout << "100.0/3.0 = " << 100.0/3.0 << endl; fout << "100.0/3.0 = " << fixed << 100.0/3.0 << endl; // close file stream fout fout.close(); return 0; } The Ohio State University
writeMultiFile.cpp . . . ofstream fout1; // declare output file stream 1 ofstream fout2; // declare output file stream 2 fout1.open("book1.txt" , ios::out); // open book1.txt fout2.open("book2.txt", ios::out); // open book2.txt if (!fout1.is_open()) { cerr << "Unable to open file book1.txt." << endl; exit(10); } if (!fout2.is_open()) { cerr << "Unable to open file book2.txt." << endl; exit(15); } The Ohio State University
writeMultiFile.cpp (cont) cout << "Writing to files book1.txt and book2.txt." << endl; // write to book1.txt fout1 << "Assets: $" << 10000 << endl; fout1 << "Liabilities: $" << 15000 << endl; // write to book2.txt fout2 << "Assets: $" << 12000 << endl; fout2 << "Liabilities: $" << 9000 << endl; fout1.close(); // close file stream fout1 fout2.close(); // close file stream fout2 return 0; } The Ohio State University
Asking for the File Name • Read the input file name into a string: #include <string> string file_name; cout << “Enter file name: “; cin >> file_name; • Unfortunately, the open() function only takes C style strings. Convert a C++ string into a C style string: file_name.c_str(); • Call fout.open() using the C style string: fout.open(file_name.c_str(), ios::out); The Ohio State University
writeFile3.cpp . . . #include <fstream> #include <string> // type string is in file “string” . . . int main() { ofstream fout; // declare an output file stream string file_name; cout << "Enter file name: "; cin >> file_name; // file_name.c_str() returns a C style string fout.open(file_name.c_str(), ios::out); // open file file_name for output if (!fout.is_open()) // check if file is opened for output { cerr << "Unable to open file " << file_name << endl; exit(10); } The Ohio State University
writeFile3.cpp (cont) cout << "Writing to file " << file_name << endl; // write text to the file fout << "Hello World!" << endl; fout << "Goodbye World!" << endl; // close file stream fout fout.close(); return 0; } The Ohio State University
Reading from Files The Ohio State University
Reading from Files: Input File Stream • To read from a file: • We need a-priori knowledge of the file format • Create an input stream object • Establish connection to a file • Check Validity • Start reading • Close the file The Ohio State University
readFile1.cpp #include <cstdlib> // function exit() is in cstdlib #include <fstream> // class ofstream() is in fstream #include <iostream> using namespace std; int main() { ifstream fin; // declare an input file stream int x; fin.open("intList1.txt" , ios::in); // open file intList.txt for input if (!fin.is_open()) // check if file is open for input { cerr << "Unable to open file intList1.txt." << endl; exit(10); } ... The Ohio State University
readFile1.cpp (cont) // read text from file fin >> x; cout << "Read integer: " << x << endl; // close file stream fin fin.close(); return 0; } The Ohio State University
… // read text from file fin >> x; cout << "Read integer: " << x << endl; … > readFile1.exe Read integer: 77 > File: intList1.txt 77 65 28 33 112 The Ohio State University
Reading from Files (1) • “Have prior knowledge of file format” • Does the input file contain integers, floating point numbers, or strings? • Files can be some combination of different types, e.g.: 523 Warren Harding 3.89 334 William McKinley 3.21 … • For each row, the first item is an integer, the second is a string, the third is a string, and the last is a double. The Ohio State University
Reading from Files (2) 2. “Create an input stream object” • Again, make sure we included the <fstream> class. • Create a variable of type ifstream. For example, ifstream fin; • The fin variable is what we would also call an “input file handler” The Ohio State University
Reading from Files (3) 3. “Establish a connection to a file” • Open the file “intList1.txt”: fin.open(“intList1.txt”, ios::in); The Ohio State University
Reading from Files (4) 4. “Check Validity” • Again, we should check that the file is able to be opened and read. // check if file is open for input if (!fin.is_open()) { cerr << "Unable to open file " << file_name << endl; exit(10); } The Ohio State University
Reading from Files (5) 5. “Start reading” • Because we know that the file contains integers, we read the data into a variable of type int : int x; // read text from file fin >> x; The Ohio State University
Reading from Files (6) 6. “Close the file” • Like before, we close the file after we are done using it: fin.close(); The Ohio State University
readFile2.cpp . . . #include <fstream> #include <string> . . . int main() { ifstream fin; // declare an input file stream string file_name; int x; cout << "Enter file name: "; cin >> file_name; fin.open(file_name.c_str(), ios::in); // open file file_name for input if (!fin.is_open()) // check if file is open for input { cerr << "Unable to open file " << file_name << endl; exit(10); } The Ohio State University
readFile2.cpp (cont) // read text from file for (int i = 1; i <= 5; i++) { fin >> x; cout << "Read integer: " << x << endl; } // close file stream fin fin.close(); return 0; } The Ohio State University
… // read text from file for (inti = 1; i <= 5; i++) { fin >> x; cout << "Read integer: " << x << endl; } … File: intList1.txt 77 65 28 33 112 > readFile2.exe Enter file name: intList1.txt Read integer: 77 Read integer: 65 Read integer: 28 Read integer: 33 Read integer: 112 > The Ohio State University
… if (!fin.is_open()) // check if file is open for input { cerr << "Unable to open file " << file_name << endl; exit(10); } … > readFile2.exe Enter file name: missing.txt Unable to open file missing.txt > The Ohio State University
… // read text from file for (inti = 1; i <= 5; i++) { fin >> x; cout << "Read integer: " << x << endl; } … File: intList3.txt 10 20 > readFile2.exe Enter file name: intList2.txt Read integer: 10 Read integer: 20 Read integer: 20 Read integer: 20 Read integer: 20 > The Ohio State University
readFile3.cpp . . . int main() { ifstream fin; // declare an input file stream string file_name; int x; cout << "Enter file name: "; cin >> file_name; fin.open(file_name.c_str(), ios::in); // open file file_name for input if (!fin.is_open()) // check if file is open for input { cerr << "Unable to open file " << file_name << endl; exit(10); } The Ohio State University
readFile3.cpp (cont) // read text from file fin >> x; while (!fin.fail()) { cout << "Read integer: " << x << endl; fin >> x; } // close file stream fin fin.close(); return 0; } The Ohio State University
fail() • The fail() function is true when the read fails. • A read fails because: • The end of file is reached. • Read error: Trying to read a character string as an integer. • Once an input operation fails, all subsequent input operations will fail. The Ohio State University
fail() • To read all integers in a file: fin >> x; while (!fin.fail()) { // Process x... fin >> x; } The Ohio State University
… // read text from file fin >> x; while (!fin.fail()) { cout << "Read integer: " << x << endl; fin >> x; } … File: intList1.txt 77 65 28 33 112 > readFile3.exe Enter file name: intList1.txt Read integer: 77 Read integer: 65 Read integer: 28 Read integer: 33 Read integer: 112 > The Ohio State University
… // read text from file fin >> x; while (!fin.fail()) { cout << "Read integer: " << x << endl; fin >> x; } … File: intList1.txt 10 20 30 40 50 60 70 > readFile3.exe Enter file name: intList2.txt Read integer: 10 Read integer: 20 Read integer: 30 Read integer: 40 Read integer: 50 Read integer: 60 Read integer: 70 > The Ohio State University
… // read text from file fin >> x; while (!fin.fail()) { cout << "Read integer: " << x << endl; fin >> x; } … File: intList3.txt 10 20 > readFile3.exe Enter file name: intList3.txt Read integer: 10 Read integer: 20 > The Ohio State University
readFile4.cpp . . . int main() { ifstream fin; // declare an input file stream string file_name; int x; cout << "Enter file name: "; cin >> file_name; fin.open(file_name.c_str(), ios::in); // open file file_name for input if (!fin.is_open()) // check if file is open for input { cerr << "Unable to open file " << file_name << endl; exit(10); } The Ohio State University
readFile4.cpp (cont) // read text from file fin >> x; while (fin) // equivalent to while (!fin.fail()) { cout << "Read integer: " << x << endl; fin >> x; } // close file stream fin fin.close(); return 0; } The Ohio State University
fail() ifstream fin; • The condition: while(fin) is equivalent to: while(!fin.fail()) The Ohio State University
fail() • The fail() function is true when the read fails. • A read fails because: • The end of file is reached. • Read error: Trying to read a character string as an integer. • Once an input operation fails, all subsequent input operations will fail. The Ohio State University