如何使用 windows api 读写文本文件

How can I read and write text files using the windows api

有很多类似的问题,但我的有点不同。我的涉及 Windows GUI。我正在使用打开文件对话框或“OPENFILENAME”。当用户单击“确定”按钮然后打开一个文本编码文件时,我希望得到的对话框结果为“确定”。我已经在 Java 中完成了,但是 UI 看起来很奇怪。所以我不确定人们是否会喜欢它。我也想学习C++,所以我需要一些帮助。我的程序中的 WM_COMMAND 消息中有一个名为“hWndEdit”的文本框。打开后,文件中的文本应该显示在我指定的文本框中。我已经使用以下代码在头文件中定义了该函数:

#include <iostream>
#include <fstream>
#include <windows.h>

using namespace std;

void OpenFile()
{
        OPENFILENAME ofn;       // common dialog box structure
        HWND hwnd = nullptr;              // owner window
        HANDLE hf;              // file handle

        // Initialize OPENFILENAME
        ZeroMemory(&ofn, sizeof(ofn));
        ofn.lStructSize = sizeof(ofn);
        ofn.hwndOwner = hwnd;
        // Set lpstrFile[0] to '[=12=]' so that GetOpenFileName does not 
        // use the contents of szFile to initialize itself.
        ofn.nMaxFile = sizeof(szFile);
        ofn.lpstrFilter = L"NoteRecorder Notes[=12=](*.recnote)[=12=]Text[=12=](*.txt)[=12=]";
        ofn.nFilterIndex = 1;
        ofn.lpstrFileTitle = NULL;
        ofn.nMaxFileTitle = 0;
        ofn.lpstrInitialDir = NULL;
        ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST;

        // Display the Open dialog box. 

        if (GetOpenFileName(&ofn) == TRUE)
        {
            hf = CreateFile(ofn.lpstrFile,
                GENERIC_READ,
                0,
                (LPSECURITY_ATTRIBUTES)NULL,
                OPEN_EXISTING,
                FILE_ATTRIBUTE_NORMAL,
                (HANDLE)NULL);
        }
}

然后我从我的 WM_COMMAND 消息中调用它:

case WM_COMMAND:
switch (wParam)
{
case 12:
OpenFile();
break;
}

但是当用户按下 OPENFILENAME 中的确定按钮时,它不会从文件中读取任何文本。我怎样才能做到这一点?

而且我想用保存文件对话框写入文件。也告诉我怎么做。

函数的主要目的GetOpenFileName and GetSaveFileName is to provide you with the filename that the user selected. However, doing the actual File Input and Output is a different issue. You can use the standard C/C++ library for that or you can use the Windows API functions, such as CreateFile, ReadFile and WriteFile

由于您似乎已经在使用函数 CreateFile,因此在验证对 CreateFile 的函数调用成功后调用 ReadFile 是有意义的(即它没有return INVALID_HANDLE_VALUE)。读取数据后,可以在数据中添加一个终止空字符(要确保内存缓冲区足够大),然后将其传递给SetDlgItemText function (if the text box is in a dialog box) or SetWindowText函数。