0

我有以下代码使用 WinAPI 中的 CreateFile 函数编写一个简单的 TXT:

#include <stdio.h>
#include <windows.h>
#include <Wincrypt.h>

#include <string.h>
#include <tchar.h>
#include <strsafe.h>
#include <iostream>


int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) {

    LPCTSTR lpFileName = L"C:\\MyTest.txt";
    DWORD dwDesiredAccess = GENERIC_READ | GENERIC_WRITE;
    DWORD dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE;
    LPSECURITY_ATTRIBUTES lpSecurityAttributes = NULL;
    DWORD dwCreationDisposition = CREATE_NEW;
    DWORD dwFlagsAndAttributes = FILE_ATTRIBUTE_NORMAL;
    HANDLE hTemplateFile = NULL;

    HANDLE C=CreateFile(lpFileName, dwDesiredAccess, dwShareMode, lpSecurityAttributes,
        dwCreationDisposition, dwFlagsAndAttributes, hTemplateFile);

    DWORD Er=GetLastError();

    char *pMsg = NULL;

    FormatMessageW(
        FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_ARGUMENT_ARRAY | FORMAT_MESSAGE_ALLOCATE_BUFFER,
        NULL,
        Er,
        LANG_SYSTEM_DEFAULT,
        (LPWSTR)&pMsg,
        0,
        NULL
        );

    if (C != INVALID_HANDLE_VALUE)

    {
        MessageBox(NULL, (LPCTSTR)pMsg, L"Explorando la API", MB_ICONINFORMATION);
    }
    else
    {

        MessageBox(NULL, (LPCTSTR)pMsg, L"Explorando la API", MB_ICONINFORMATION);
    }


    CloseHandle(C);

}

问题是:如何使用StringCchCat函数将自定义字符串传递给 lpFile 名称?

我想从注册表项中读取任何数字(使用 RegQueryValue)并为文件命名。例如,如果我从 DemoValue 中读取“1”,则 TXT 名称将是:MyText1.txt 或 MyText(1).txt。

你能帮助我吗?谢谢!

4

1 回答 1

1

您可能想要使用 StringCbPrintf 而不是 StringCchCat。

int const filenamesize = 30;
TCHAR filename[filenamesize]; 
StringCbPrintf(filename, filenamesize * sizeof(TCHAR), TEXT("Myfile(%d).txt", somevalue);
// e.g: filename contains a "Myfile(1).txt" if 'somevalue' contains 1
...
HANDLE c = CreateFile(filename, ...) ;
于 2013-09-13T13:03:45.540 回答