简体   繁体   中英

MFC C++: How to actually save a certain file to the system, not just open a save as dialog box

I searched everywhere but I can't find sample on how to actually save a file to the system. Threads about opening a Save File dialog box can be read in numerous sites but the successful saving of the user created file to a user selected path is always cut (//add your code here). Please bear with me as I am new in C++ (MFC).

I know I need to actually code the saving of the data to the file path but I just don't know how.

Code snippet (via CFileDialog):

void CTryDlg::OnBnClickedSaveAs()
{
    CFileDialog dlg(FALSE);
    dlg.m_ofn.nMaxFile = MAX_PATH;
    dlg.m_ofn.lpstrFilter = _T("Text Files (*.txt)\0*.txt\0All Files (*.*)\0*.*\0\0");
    dlg.m_ofn.lpstrTitle = _T("Save File As");
    CString filename;
    if (dlg.DoModal() == IDOK)
    {
        filename = dlg.GetPathName(); // return full path and filename
        //write your sample code here to save the file to the user selected path
    }                                                                                           
}

Code snippet via GetSaveFileName():

OPENFILENAME SfnInit()
{
    OPENFILENAME t_sfn;

    char szFileName[MAX_PATH] = "";
    ZeroMemory(&t_sfn, sizeof(t_sfn));
    t_sfn.lStructSize = sizeof(t_sfn);
    t_sfn.hwndOwner = NULL;
    t_sfn.lpstrFilter = _T("Text file\0*.txt\0");
    t_sfn.lpstrFile = szFileName;
    t_sfn.lpstrTitle = _T("Save As\0");
    t_sfn.nMaxFile = MAX_PATH;
    t_sfn.Flags = OFN_EXPLORER | OFN_FILEMUSTEXIST | OFN_HIDEREADONLY;
    t_sfn.lpstrDefExt = _T("Text file\0*.txt\0");

    if (GetSaveFileName(&t_sfn2) != true)
    {
        AfxMessageBox(_T("Saving file canceled!"));
    }
    else
    {
        //write your sample code here to save the file to the user selected path
    }
}

Anybody who can provide a very simple sample code that could actually save a user desired file (ex: text file) to the user selected path will be greatly appreciated. I have also read that the program should run as administrator.

Thank you.

Since you are using MFC, I would recommend sticking with MFC classes for such file I/O.

Sadly, I am using VS 2008, but here is the class hierarchy for CFile:

If it's a text file, using/deriving from CStdioFile makes sense. It has the basic ReadString WriteString methods.

However, if you are wanting to serialize something derived from CDocument (Document/View architecture), you will want to utilize streams, possibly with schemas/versioning to go with your serialization. That's a completely different topic/answer.

EDIT: duh - here's a simple CStdioFile output

        CFileDialog fd(FALSE, "txt", "MyFile.txt", OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT, "Text files (*.txt)|*.txt|All files (*.*)|*.*", this);
        if (fd.DoModal() == IDOK)
            {
            CStdioFile fOut(fd.GetPathName(), CFile::modeCreate | CFile::modeWrite);
            for (int i = 0; i < asData.GetSize(); i++)
                {
                fOut.WriteString(asData[i] + '\n');
                }
            fOut.Close();
            }

Here is a very basic sample:

...
if (dlg.DoModal() == IDOK)
{
    filename = dlg.GetPathName(); // return full path and filename

    FILE *file = fopen(filename, "w");    // open file for writing

    if (file == NULL)
      AfxMessageBox("File couild not be created."};
    else
    {
      // file could be created, write something
      fprintf(file, "Some text\n");

      // and close the file
      fclose(file);
    }
}
...

This will write "some text" into the file whose name has been provided by the user with the CFileDialog file picker.

In real world you need to write whatever text according to the data of your program.

This is really most basic knowledge.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM