为要保存的文件添加扩展名
Add an extention to the file you want to save
问题是我在保存文件名时需要添加扩展名。像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;
}
然后,当我想保存我的结果时,我试图使用这种结构:
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);
}
这是我试图解决问题
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] = ' ';
ofn.nMaxFile = MAX_PATH;
ofn.lpstrFilter = _T("All Files *.* Text files *.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(检查编译器标志?),fstream::open()
函数可以很好地处理字符串。因此无需通过c_str()
。然后,您可以按照自己的意愿在字符串上使用operator+
:
buf_stream.open(bufFile);
out_stream.open(outFile);
...
outfile.open(filename + ".txt");
备注:当您声明流的构造函数时已经知道文件名时,您可以立即将其提供给它。因此不需要调用单独的open()
如果不能使用C++11,则使用临时字符串进行连接:
outfile.open (string(filename+".tst").c_str());
相关文章:
- C++中的VLA,扩展名为std=C++11
- 如何按文件扩展名引用文件夹中的文件
- VSCode 中带有 C/C++ 扩展名的多行注释缩进错误
- 为什么我无法打开/读取从 Python 调用的 C 扩展名中的 txt 文件?
- 使用Boost文件系统C++将具有特定扩展名的文件的名称保存在特定文件夹中
- 共享库 (.so) 没有扩展名的 Linux 可执行文件之间的区别?
- Visual Studio Code "variable " u8 的 C/C++ 扩展名 " " 不是类型名称"
- Makefile by ocaml 和 cpp 扩展名
- CMake 不编译具有非标准扩展名的文件
- Visual Studio 2019 - 设置文件类型的默认扩展名
- 如何在 Windows 上获取带有 c++ 且没有 <dirent.h> 的特定扩展名的所有文件的列表
- 谁能告诉我,程序中的错误是什么?该程序仅用于获取文件扩展名
- 如何在 vscode 扩展名中检索 C/C++ 文件的编译命令
- 通过cMake使用具有自定义文件扩展名的共享库
- 如何在 CMake 中"override"文件的按扩展名类型
- 在另一个字符串中插入文件扩展名之前的字符串
- 使用CryptoApi将扩展名添加到证书中
- 为要保存的文件添加扩展名
- 有没有一种方法可以在Linux上使用QFileDialog自动为文件添加扩展名
- Rename()函数在尝试向文件添加扩展名时不起作用