如何select文件保存的位置?
How to select the location that file is being saved to?
我对 C++ 比较陌生,我希望能够打开文件资源管理器并能够select 保存到的位置。它目前保存在与 c++ 文件相同的文件夹中。
我该怎么做?谢谢
std::ofstream testFile;
testFile.open("Test.csv");
testFile << "Test";
testFile.close();
您可能需要类似这样的东西:
#include <Windows.h>
OPENFILENAME ofn;
char szFileName[MAX_PATH];
strcpy(szFileName, "Test.csv");
ZeroMemory(&ofn, sizeof(ofn));
ofn.lStructSize = sizeof(ofn);
ofn.hwndOwner = NULL;
ofn.lpstrFilter = (LPCSTR)"All Files (*.*)";
ofn.lpstrFile = (LPSTR)szFileName;
ofn.nMaxFile = MAX_PATH;
ofn.Flags = OFN_EXPLORER;
ofn.lpstrDefExt = (LPCSTR)"csv";
if (GetSaveFileName(&ofn))
{
std::string pathToFile = ofn.lpstrFile;
// save you file here, using pathToFile
}
else
{
puts("Something went wrong");
}
您打开默认文件名为 "Test.csv" 的文件资源管理器。然后,您可以 select 目录并在按 "Save" 后您将获得全局文件路径。此路径稍后可用于保存您的文件。
此外,您可能认为有用的文档:
试试这个(虽然没有测试):
void CMyMFCDlg::OnBnClickedButtonBrowseCvsFile()
{
CFileDialog dlg(TRUE);
dlg.m_ofn.lpstrFilter = L"cvs files (*.cvs)[=10=]*.cvs[=10=][=10=]";
dlg.m_ofn.lpstrInitialDir = L"D:\MyDefaultDir\"; //optional line
dlg.m_ofn.lpstrTitle = L"Open cvs file";
if (dlg.DoModal() == IDOK)
{
CString filenamewithpath = dlg.GetPathName();
std::ofstream testFile;
testFile.open(filenamewithpath.GetString()); // unicode
//testFile.open(CStringA(filenamewithpath).GetString()); //multibyte
testFile << "Test";
testFile.close();
}
}
我对 C++ 比较陌生,我希望能够打开文件资源管理器并能够select 保存到的位置。它目前保存在与 c++ 文件相同的文件夹中。 我该怎么做?谢谢
std::ofstream testFile;
testFile.open("Test.csv");
testFile << "Test";
testFile.close();
您可能需要类似这样的东西:
#include <Windows.h>
OPENFILENAME ofn;
char szFileName[MAX_PATH];
strcpy(szFileName, "Test.csv");
ZeroMemory(&ofn, sizeof(ofn));
ofn.lStructSize = sizeof(ofn);
ofn.hwndOwner = NULL;
ofn.lpstrFilter = (LPCSTR)"All Files (*.*)";
ofn.lpstrFile = (LPSTR)szFileName;
ofn.nMaxFile = MAX_PATH;
ofn.Flags = OFN_EXPLORER;
ofn.lpstrDefExt = (LPCSTR)"csv";
if (GetSaveFileName(&ofn))
{
std::string pathToFile = ofn.lpstrFile;
// save you file here, using pathToFile
}
else
{
puts("Something went wrong");
}
您打开默认文件名为 "Test.csv" 的文件资源管理器。然后,您可以 select 目录并在按 "Save" 后您将获得全局文件路径。此路径稍后可用于保存您的文件。
此外,您可能认为有用的文档:
试试这个(虽然没有测试):
void CMyMFCDlg::OnBnClickedButtonBrowseCvsFile()
{
CFileDialog dlg(TRUE);
dlg.m_ofn.lpstrFilter = L"cvs files (*.cvs)[=10=]*.cvs[=10=][=10=]";
dlg.m_ofn.lpstrInitialDir = L"D:\MyDefaultDir\"; //optional line
dlg.m_ofn.lpstrTitle = L"Open cvs file";
if (dlg.DoModal() == IDOK)
{
CString filenamewithpath = dlg.GetPathName();
std::ofstream testFile;
testFile.open(filenamewithpath.GetString()); // unicode
//testFile.open(CStringA(filenamewithpath).GetString()); //multibyte
testFile << "Test";
testFile.close();
}
}