Code from Grocery List Problem
Function That Reads a File
// Used by ListBox client to read a text file into the list box.
void Exam5aApp::LoadTextFile ()
{
char buf[255+1];
ifstream *inStream;
TListBox *client = TYPESAFE_DOWNCAST(GetMainWindow()->GetClientWindow(), TListBox);
// Only work if the client class is a TListBox.
if (client) {
client->ClearList();
inStream = new ifstream(FileData.FileName);
while (inStream->good()) {
inStream->getline(buf, sizeof(buf) - 1);
if (inStream->good())
client->AddString(buf);
}
// Return an error message if we had a stream error and it wasn't the eof.
if (inStream->bad() && !inStream->eof()) {
string msgTemplate(*this, IDS_UNABLEREAD);
char* msg = new char[MAXPATH + msgTemplate.length()];
wsprintf(msg, msgTemplate.c_str(), *FileData.FileName);
GetMainWindow()->MessageBox(msg, GetName(), MB_ICONEXCLAMATION | MB_OK);
delete msg;
}
delete inStream;
}
}
Save Routines
void
Exam5aListBox::Save()
{
if (strlen(FileData.FileName)==0) {
SaveAs();
return;
}
ofstream *outStream = new ofstream(FileData.FileName);
int howMany = GetCount();
for (int i = 0;i < howMany;i++)
{
SetSelIndex(i);
char buff[255];
GetSelString(buff,255);
strcat(buff,"\n");//insert end of line marker
outStream->write(buff,strlen(buff));
}
outStream->close();
delete outStream;
}
//
// saves the contents of the TEdit child control into a file whose name
// is retrieved from the user, through execution of a "Save" file dialog
//
// returns true if the file was saved
//
int
Exam5aListBox::SaveAs()
{
FileData.SetFilter("Grocery files (*.DAT)|*.DAT|AllFiles (*.*)|*.*|");
int result;
if (result = TFileSaveDialog(this, FileData).Execute() == IDOK)
{
setFile(FileData);
Save();
return 1;
}
if (result == IDCANCEL)
{
string msgTemplate(GetModule()->LoadString(IDS_UNABLEWRITE));
char* msg = new char[50 + msgTemplate.length()];
wsprintf(msg, msgTemplate.c_str(), FileData.FileName);
MessageBox(msg, GetApplication()->GetName(), MB_ICONEXCLAMATION | MB_OK);
delete msg;
}
return 0;
}
void Exam5aListBox::cmFileSave ()
{
// INSERT>> Your code here.
Save();
}
void Exam5aListBox::cmSaveAs ()
{
// INSERT>> Your code here.
SaveAs();
}