0

I am relatively new to C++ and I want to be able to open the file explorer and be able to select the location to be saved to. It currently saves within the same folder as the c++ files. How do I go about this? Thanks.

std::ofstream testFile;
testFile.open("Test.csv");
testFile << "Test";
testFile.close();
Yksisarvinen
  • 18,008
  • 2
  • 24
  • 52
  • The file is created successfully within the current directory, however I want to be able to select the directory the file is being saved to and I am unsure how to do this. – Nathan Joel Aug 08 '19 at 09:36
  • You have added the tag `mfc`. Have you searched the Microsoft documentation about MFC to see if there's a file or directory dialog component available? – Some programmer dude Aug 08 '19 at 09:53
  • I think you can find the solution in this [old post](https://stackoverflow.com/questions/17836903/how-to-open-folder-with-c) – aleci Aug 08 '19 at 09:59

2 Answers2

1

Try this ( not tested though):

void CMyMFCDlg::OnBnClickedButtonBrowseCvsFile()
{
    CFileDialog dlg(TRUE);
    dlg.m_ofn.lpstrFilter = L"cvs files (*.cvs)\0*.cvs\0\0";
    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();
    }
}
seccpur
  • 4,996
  • 2
  • 13
  • 21
0

You probably need something similar to this:

#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");
}

You open file explorer with default file name of "Test.csv". Then, you can select the directory and after pressing "Save" you get the global file path. This path could be later used to save you file.

Also, docs that you may consider useful:

GetSaveFileName

OPENFILENAME

Dmsc
  • 56
  • 4