保存/加载对话框文本文件



我创建了一个带有编辑框和两个按钮的对话框。保存并加载按钮。

单击保存时,我想将编辑框中的文本保存到 txt 文件中,然后加载,将 txt 文件加载到编辑框中。现在保存/加载按钮似乎不起作用。保存按钮似乎创建了一个名为"u"的文件,而不是保存到所选文件,并且加载按钮在选择文件后不执行任何操作。这是我到目前为止所拥有的:

#include <Windows.h>
#include <commdlg.h>
#include <fstream>
#include <string>
#include "resource.h"
using namespace std;
// Globals
HWND ghMainWnd = 0;
OPENFILENAME ofn;

// Handles
static HWND hEditBox    = 0;
static HWND hSaveButton = 0;
static HWND hLoadButton = 0;
// Contains file.
char szFile[100];
void save()
{
    char text[260];
    GetWindowText( hEditBox, text, 260 );
    ofstream saveFile( szFile, ios_base::binary );
    int length = strlen( text );
    saveFile.write( (char*)&length, sizeof(length) );
    saveFile.write( text, length );
}
void load()
{
    char text[260];
    ifstream loadFile( szFile, ios_base::binary );
    int length = 0;
    loadFile.read((char*)&length, sizeof(length));
    loadFile.read( text, length );
    text[length] = '';
    SetWindowText( hEditBox, text );
}
BOOL CALLBACK
WndProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam )
{
    ZeroMemory( &ofn , sizeof( ofn ) );
    ofn.lStructSize     = sizeof( ofn );
    ofn.hwndOwner       = hWnd;
    ofn.lpstrFile       = szFile;
    ofn.lpstrFile[0]    = '';
    ofn.nMaxFile        = sizeof( szFile );
    ofn.lpstrFilter     = "All*.*Text*.TXT";
    ofn.nFilterIndex    = 1;
    ofn.lpstrFileTitle  = "Open/Save File Dialog";
    ofn.nMaxFileTitle   = 0;
    ofn.lpstrInitialDir = NULL;
    ofn.Flags           = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST;
    switch( msg )
    {
    case WM_INITDIALOG:
        hEditBox    = GetDlgItem( ghMainWnd, IDC_EDIT );
        hSaveButton = GetDlgItem( ghMainWnd, ID_SAVE );
        hLoadButton = GetDlgItem( ghMainWnd, ID_OPEN );
    return true;
    case WM_COMMAND:
        switch( LOWORD( wParam ) )
        {
        case ID_SAVE:
            GetSaveFileName( &ofn );
            save();
        return true;
        case ID_OPEN:
            GetOpenFileName( &ofn );
            load();
        return true;
        }
    return true;
    case WM_CLOSE:
        DestroyWindow( hWnd );
    return true;
    case WM_DESTROY:
        PostQuitMessage( 0 );
    return true;
    }
    return false;
}
INT WINAPI
WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR cmdLine, int showCmd )
{
    ghMainWnd = CreateDialog( hInstance, MAKEINTRESOURCE( IDD_TXTDLG ), 0, WndProc );
    ShowWindow( ghMainWnd, showCmd );
    MSG msg;
    ZeroMemory( &msg, sizeof( MSG ) );
    while( GetMessage( &msg, 0, 0, 0 ) )
    {
        if( ghMainWnd == 0 || !IsDialogMessage( ghMainWnd, &msg ) )
        {
            TranslateMessage( &msg );
            DispatchMessage( &msg );
        }
    }
    return (int)msg.wParam;
}

查看正在发生的事情的最佳方法是在调用之前显示文件名。您可以在调试器中执行此操作并查看它是什么,看看它是否错误。它将帮助您意识到问题是否出在调用函数或读取名称方面。我不记得char可以与GetWindowText一起使用(也许在非Unicode中是可以的)。

您还需要添加处理以检查字符串是否为空以防万一。甚至可以验证名称是否有效。

最新更新