Reputation: 35
The problem is that I need to add an extension to the file name when I save it. Solution like outfile.open(filename + ".txt")
doesn't seems to work in my case.
There is my code:
SaveFileDialog* saveFileDialog1 = new SaveFileDialog();
int saveAs(const string& outFileName)
{
string bufFile("C:\\Windows\\tmp.XXXXXX");
string outFile(saveFileDialog1->NewFileName);
string line;
string val;
ifstream buf_stream;
ofstream out_stream;
buf_stream.open(bufFile.c_str());
out_stream.open(outFile.c_str());
if (buf_stream)
{
while (!buf_stream.eof())
{
getline(buf_stream, line);
buf_stream >> val;
out_stream << val<<endl;
}
}
buf_stream.close();
out_stream.close();
remove("C:\\Windows\\tmp.XXXXXX");
return 0;
}
And then I'm trying to use that construction when I want to save result I have:
case IDM_FILE_SAVE:
{
saveFileDialog1;
saveFileDialog1->ShowDialog();
saveFileDialog1->FilterIndex1 = 1;
saveFileDialog1->Flags1 |= OFN_SHOWHELP;
saveFileDialog1->InitialDir1 = _T("C:\\Windows\\");
saveFileDialog1->Title1 = _T("Save File");
int retval = saveAs(saveFileDialog1->NewFileName);
}
There is my attempt to solve problem
SaveFileDialog::SaveFileDialog(void)
{
this->DefaultExtension1 = 0;
this->NewFileName = new TCHAR[MAX_PATH + TCHAR(".txt")];
this->FilterIndex1 = 1;
this->Flags1 = OFN_OVERWRITEPROMPT;
this->InitialDir1 = 0;
this->Owner1 = 0;
this->Title1 = 0;
this->RestoreDirectory = true;
}
bool SaveFileDialog::ShowDialog()
{
OPENFILENAME ofn;
TCHAR szFile[MAX_PATH] = "";
ZeroMemory(&ofn, sizeof(ofn));
ofn.lStructSize = sizeof(ofn);
ofn.hwndOwner = this->Owner1;
ofn.lpstrDefExt = this->DefaultExtension1;
ofn.lpstrFile = this->NewFileName;
ofn.lpstrFile[0] = '\0';
ofn.nMaxFile = MAX_PATH;
ofn.lpstrFilter = _T("All Files\0*.*\0Text files\0*.txt");
ofn.nFilterIndex = this->FilterIndex1;
ofn.lpstrInitialDir = this->InitialDir1;
ofn.lpstrTitle = this->Title1;
ofn.Flags = this->Flags1;
GetSaveFileName(&ofn);
if (_tcslen(this->NewFileName) == 0) return false;
return true;
}
Any suggestions will be greatly appreciated.
Upvotes: 1
Views: 412
Reputation: 73542
With c++11 (check your compiler flags ?) the fstream::open()
function works perfectly well with strings. So no need to pass through c_str()
. Then you can use the operator+
on strings as you intended:
buf_stream.open(bufFile);
out_stream.open(outFile);
...
outfile.open(filename + ".txt");
Remark: you can immediately give the filename to the constructor of the stream when it's already known at the time you declare it. It's hence not required to call a separate open()
.
If you can't use C++11, then use a temporary string for the concatenation:
outfile.open (string(filename+".tst").c_str());
Upvotes: 1