我有以下代码使用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。
你能帮帮我吗?谢谢!答案 0 :(得分: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, ...) ;