Reputation: 867
I have the following code to write a simple TXT using the CreateFile function from the WinAPI:
#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);
}
The question is: How can I use StringCchCat
function to pass a customized string to the lpFile name?
I would like to read any number from a Registry Key (Using the RegQueryValue) and give a name to the file. For example, if I read "1" form a DemoValue, the TXT name would be: MyText1.txt or MyText(1).txt.
Can you help me? Thanks!
Upvotes: 0
Views: 262
Reputation: 50882
You probably want to use StringCbPrintf instead of 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, ...) ;
Upvotes: 1