// Native_WrtieTextFile.cpp : Defines the entry point for the console application. /* _____________________________________________________________________________ Learning C++: Lesson 5 File I/O: Writing to a textfile Ron Kessler Created 1/4/2017 Native Version This little program shows how to read a simple text file. This little program shows how to work with File IO. You are asked to add a new contact and then it is saved to disk. The program then reads the updated file and displays the names. You can add a new text file to your project by: 1. Rt. clicking on the project in Solution Explorer. 2. Choose ADD | New Item 3. Select Utility | Textfile from the dialog box. 4. Name it using the .txt file extension Run using CTL-F5 ___________________________________________________________________________ */ #include "stdafx.h" #include //add this for IO #include #include using namespace std; int main () { cout << "Learning About Writing to Text Files\n\n"; cout << "Enter a new contact : "; string newContact; getline (cin, newContact); //---add stuff to current file ofstream myWriter ("contacts.txt", ios::app); //of = output file (write) and append if (myWriter.is_open ()) { myWriter << newContact << "\n"; } else { cout << "Could not write to the file!" << '\n'; return 0; } myWriter.close (); //BE SURE TO CLOSE AFTER WRITING! //************************READING NEW RECORDS************************** //---now display the file data system("cls"); cout << "Here Is The List Of Your Contacts: \n\n\n"; ifstream myReader ("contacts.txt"); //open file for reading (i= input) string lineFromFile; if (myReader.is_open ()) //make sure file can be opened { while (getline (myReader, lineFromFile)) //read to end of file { cout << lineFromFile << "\n"; //print out each line } } else cout << "Unable to read your file"; myReader.close (); return 0; }