// FileIO_WriteTetFiles.cpp : main project file. /* Working With TextFiles ________________________________________________ Learning C++/CLI Ron Kessler Created 7/24/2016 This little program shows how to use: File IO with the StreamWriter to save data to a textfile. Includes structured error handling _________________________________________________ */ #include "stdafx.h" using namespace System; using namespace System::IO; //be sure to add this ConsoleKeyInfo cki; //so we can trap keys int Ready2Quit(); //define helper function here void ReadMyFile(); //define helper function here int main(array ^args) { String^ myTitle = "Welcome to Learning About Saving Data to a File\n"; String^ showPrompt = "Add five inventory items now:\n"; //---define our objects here String^ diskFile = "inventory.txt"; StreamWriter^ sw; //define streamwriter here without instaniating //---print out a nice welcome Console::WriteLine(myTitle); Console::WriteLine(showPrompt); //---now get some items to save and store in an array array^ myItems = gcnew array(5); for (int x = 0; x < 5; x++) //get 5 items and add to the array { myItems[x] = Console::ReadLine(); } Array::Sort(myItems); //sort the items to be nice! Console::WriteLine("\n\nData has been read. Press any key to save to disk....\n"); Console::ReadLine(); try { sw = gcnew StreamWriter(diskFile, false); //false = DO NOT APPEND for each(String^ whichItem in myItems) //cycle through the items in the array and save each to disk { sw->WriteLine(whichItem); } if (sw != nullptr) //can't close an object that does not exist! sw->Close(); //close here so we can read the file. Can't read a file if it is still open from writing! Console::Write("Your data has been saved.\n\n"); Ready2Quit(); } catch (Exception^ e) { Console::Write("An error occurred while saving....\n" + e->Message); Ready2Quit(); } finally //this block runs when the app is closing! { if (sw != nullptr) sw->Close(); //make sure to always close the writer } } #pragma region Helper Function int Ready2Quit() { Console::Write("\nPress Escape (Esc) to quit.\n or ENTER to read the file.\n\n"); cki = Console::ReadKey(); if (cki.Key == ConsoleKey::Escape) return 0; else if (cki.Key == ConsoleKey::Enter) ReadMyFile(); } void ReadMyFile() { Console::Clear(); Console::WriteLine("Here are the items you saved.\n\n"); //---define our objects here String^ diskFile = "inventory.txt"; StreamReader^ sr; //define streamreader here without instaniating try { sr = gcnew StreamReader(diskFile); while (sr->Peek() != -1) { String^ dataFromFile = sr->ReadLine(); Console::WriteLine(dataFromFile); } //---quit? Ready2Quit(); } catch (Exception^ e) { Console::Write("An error occurred while reading....\n" + e->Message); Ready2Quit(); } finally { if (sr != nullptr) sr->Close(); //make sure to always close the reader } } #pragma endregion