Lecture 24

File I/O

Reading

p500-506, 506-516

Alternate way to execute programs

1. Locate your executable file: It may be in your Visual Studio Projects\project_name\Debug folder. (in may be in other name, you can do a search to find out where it is).
2. using window explorer, locate the folder and click on the executable file.
Or
1. Locate your executable file: It may be in your Visual Studio Projects\project_name\Debug folder.
2. Run DOS prompt by clicking on DOS command. Change to the folder where the executable file locates.
3. You can see the executable file.
You can type programname.exe to execute the program.
Here is the code
 #include<iostream>
using namespace std;

int main() {
    cout << "Hello World.\n";

    // the following few lines are useless
    // it mainly used to prevent the closure of DOS window
    char ch;
    cout << "Press any key to stop the program. ";
    cin >> ch; 

    return 0;
}     
      
      

File

Write to a file

Example
#include<iostream>
      #include<fstream> // include the library
using namespace std;

int main() {
    ofstream outStream; // define an output file stream
    outStream.open("hello.txt"); // open a file named hello.txt
    outStream << "Hello World"; // write to the file
    outStream.close(); // close the output file stream
    return 0;
}
      

Output Explanation

Read from a file

Example
#include<iostream>
#include<fstream> // include the library using namespace std; int main() { ifstream inStream; // declare an ifstream inStream.open("number.txt"); // open file number.txt for reading int a; inStream >> a; // read from the file cout << a << endl; inStream.close(); // close the stream return 0; }
Name the following file number.txt
1999
Where to put the file? or
Output
1999

Explanation One more example
#include<iostream>
#include<fstream> // include the library using namespace std; int main() { int size = 6; // assume we know that there only 6 students ifstream inStream; // declare an ifstream inStream.open("student.txt"); // open file student.txt for reading ofstream outStream; // declare an ofstream outStream.open("female.txt"); // open file female.txt char name[20]; char gender; for(int i = 0; i < size; i++) { inStream >> name; // read the name inStream >> gender; // read the gender if(gender == 'F') { outStream << name << endl; // write the names to the file } } inStream.close(); // close the stream
outStream.close(); // close the stream
return 0; }

Here is the file named student.txt
Betty F
Eric M
Lori F
Charles M
Mary F
Ken M

Here is the output named female.txt
Betty
Lori
Mary