_tfopen_s在传递常量字符串时可以起作用,但在传递变量时却不能

时间:2017-04-04 07:49:34

标签: c++ memory

当我在UNICODE环境中打开文件时,它适用于:   _tfopen_s(fp,TEXT("C://puttty.exe"),TEXT("rb"));
但是在下面它不适用于函数:

#include "stdafx.h"

HINSTANCE hInst;

INT_PTR CALLBACK    MainDlgProc(HWND, UINT, WPARAM, LPARAM);


struct  _PE_INFO
{
    TCHAR* szFileName;
};

class PEFile
{
public:
    _PE_INFO pe_info;

public:
    PEFile();
    virtual ~PEFile();

public:
    int ReadPEFile(_PE_INFO& pe);
    VOID PEFile::OpenFile(LPOPENFILENAME lpOpenFileName, HWND hWndDlg);
};

PEFile::PEFile()
{

}

PEFile::~PEFile()
{

}

int PEFile::ReadPEFile(_PE_INFO& pe)
{
    FILE* fp = NULL;
    errno_t t = _tfopen_s(&fp, pe.szFileName, TEXT("rb"));
    return t;
}

VOID PEFile::OpenFile(LPOPENFILENAME lpOpenFileName, HWND hWndDlg)
{
    TCHAR szPeFileExt[100] = TEXT("*.exe;*.dll;*.scr;*.drv;*.sys");
    TCHAR szFileName[256];
    memset(szFileName, 0, 256);
    memset(lpOpenFileName, 0, sizeof(*lpOpenFileName));
    lpOpenFileName->lStructSize = sizeof(*lpOpenFileName);
    lpOpenFileName->Flags = OFN_FILEMUSTEXIST | OFN_PATHMUSTEXIST;
    lpOpenFileName->hwndOwner = hWndDlg;
    lpOpenFileName->lpstrFilter = szPeFileExt;
    lpOpenFileName->lpstrFile = szFileName;
    lpOpenFileName->nMaxFile = MAX_PATH;

    GetOpenFileName(lpOpenFileName);
}

INT_PTR CALLBACK MainDlgProc(HWND hDlg, UINT uMessage, WPARAM wParam, LPARAM lParam)
{
    PEFile test;
    OPENFILENAME stOpenFileName = { 0 };
    int t = -1;
    //int t = test.ReadPEFile(test.pe_info);
    switch (uMessage)
    {
    case WM_CLOSE:
        EndDialog(hDlg, 0);
        break;
    case WM_INITDIALOG:
        test.OpenFile(&stOpenFileName,hDlg);
        test.pe_info.szFileName = stOpenFileName.lpstrFile;
        t = test.ReadPEFile(test.pe_info);
        break;
    default:
        break;
    }
    return 0;
}



int APIENTRY wWinMain(_In_ HINSTANCE hInstance,
    _In_opt_ HINSTANCE hPrevInstance,
    _In_ LPWSTR    lpCmdLine,
    _In_ int       nCmdShow)
{
    //test.pe_info.szFileName = TEXT("C:\\putty.exe");
    DialogBox(hInst, MAKEINTRESOURCE(IDD_DIALOG1), NULL, MainDlgProc);
    getchar();
    return 0;
}

我在调试时跟踪了内存,我看到在_tfopen_s的过程中更改了szFileName,然后显示该文件不存在或系统正忙。

我想也许这是课堂上的问题..感谢您的帮助!

0 个答案:

没有答案