Lesson 13: File Input / Output

[spoiler title=”Lesson Video”]
Direct Download of Video (For mobile / offline viewing)(right click > save target as)


[/spoiler]

[spoiler title=”Lesson Source Code”]

#include 
#include 
#include 
 
using namespace std;
 
 
int main(){
 
  // cout << "String" ;
  // cin >> variable;
  string fileName = "Text.txt";
  string fileName2 = "Text2.txt";
  string str = "";
 
  ofstream fout;
  ifstream fin;
  int wordCount = 0, lineCount=0;
 
  //getline(cin, str);
 
  fin.open(fileName);
  fout.open(fileName2);
  while (fin >> str){
    if (str != "Bird"){
      fout << str << endl;
    }
  }
  fin.close();
 
  /*while (getline(fin, str)){
    cout << str << endl;
    lineCount++;
  }*/
 
  fin.open(fileName2);
  while (fin >> str){
    cout << str << endl;
    wordCount++;
  }
 
  cout << "The number of words in this file was: " << wordCount << endl;
  //cout << "The number of lines in this file was: " << lineCount << endl;
 
  system("PAUSE");
  return 0;
}
 
/*
CONTENTS OF Text.txt
Cat Dog Bird
Cat
Dog
Bird
*/

[/spoiler]

Homework: Homework available here: https://beginnerscpp.com/forums/index.php/topic,73.0.html



File Input / Output
File input / output has been one of the most confusing topics for students. By the time they make their way to me they have tried slogging through assignments for hours. A few days ago I had a student approach me that spoke of working for 7 hours without being any closer to solving his solution. His code was a mess, and he was unable to explain how he had gotten to that point. So let me tell you before I even begin showing you code. There are differences between handling files and handling console input (via cin / cout) but for the most part, the two are VERY similar.

#include 
...
ifstream fin; //input filestream
ofstream fout; //output filestream
fin.open(fileName);
string str="";
fin >> str; //read once from the file until whitespace
getline(fin,str); //Read a line from the file until \n
fin.close(); //Close the file to free up memory
fout.open(fileName); //Open a file for output
fout << "The sum of 1+2 = " << 1+2;
fout.close();
...

As you can see in the above code, all we need to do to read a line or to read in a single word is EXTREMELY similar in syntax to the usage of cin / cout that you should be familiar with by now. To read an entire file in this manner, we just expand the single statements into a while statement:

while(getline(fin,str)) { //do line-by-line stuff here }
while(fin >> str ){ //do word-by-word logic here }