C++ 向要保存的文件添加扩展名
问题是,我需要在保存文件名时为其添加扩展名。像C++ 向要保存的文件添加扩展名,c++,winapi,file-extension,savefiledialog,C++,Winapi,File Extension,Savefiledialog,问题是,我需要在保存文件名时为其添加扩展名。像outfile.open(filename+“.txt”)这样的解决方案在我的案例中似乎不起作用。 这是我的代码: SaveFileDialog* saveFileDialog1 = new SaveFileDialog(); int saveAs(const string& outFileName) { string bufFile("C:\\Windows\\tmp.XXXXXX"); string outFile(sa
outfile.open(filename+“.txt”)
这样的解决方案在我的案例中似乎不起作用。
这是我的代码:
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;
}
我试图解决这个问题
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;
}
如有任何建议,将不胜感激 使用c++11(检查编译器标志?)该函数可以很好地处理字符串。因此,无需通过
c_str()
。然后,您可以按预期在字符串上使用:
buf_stream.open(bufFile);
out_stream.open(outFile);
...
outfile.open(filename + ".txt");
备注:您可以在声明文件名时,立即将文件名提供给流的构造函数。因此,不需要调用单独的open()
如果不能使用C++11,请使用临时字符串进行连接:
outfile.open (string(filename+".tst").c_str());
为什么
outfile.open(filename+“.txt”)
对您不起作用?当我键入这个out\u stream.open(outfile.c\u str()+“.txt”)
VS返回错误:1 IntelliSense:表达式必须具有整数或非作用域枚举type@RuslanMuhamadiarov您正在尝试添加两个指针。省去“.c_str()”。谢谢你,伙计!我很高兴对你的评论投赞成票,但很抱歉,我不能投,因为它现在起作用了!感谢上帝,我花了好几个小时试图解决这个问题:(
outfile.open (string(filename+".tst").c_str());