// FileIO-TextFiles.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 StreamReader to read data from 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 int main(array ^args) { String^ myTitle = "Welcome to Learning About File IO\n"; String^ showData = "Here is the contents of your file:\n"; //---define our objects here String^ diskFile = "inventory.txt"; StreamReader^ sr; //define streamreader here without instaniating //---print out a nice welcome Console::WriteLine(myTitle); Console::WriteLine(showData); 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 region Helper Function int Ready2Quit() { Console::Write("\nPress Escape (Esc) to quit.\n"); cki = Console::ReadKey(); if (cki.Key == ConsoleKey::Escape) return 0; } #pragma endregion