¿Cómo crear un archivo usando la API de Windows?

I want to create a text file using windows API. I studied about

HANDLE CreateFile(
LPCTSTR lpFileName, 
DWORD dwDesiredAccess, 
DWORD dwShareMode, 
LPSECURITY_ATTRIBUTES lpSecurityAttributes, 
DWORD dwCreationDispostion , 
DWORD dwFlagsAndAttributes, 
HANDLE hTemplateFile); 

I can't understand how to pass the first parameter to create a file. I tried to use data-type FILE and pass it's pointer as first parameter but it's showing incompatible with LPCTSTR. Can anybody tell me how to do it? I am new in using windows API. Thanks in advance.

preguntado el 09 de enero de 11 a las 07:01

3 Respuestas

LPCTSTR es el mismo que const TCHAR* ("Long Pointer to a Constant TCHAR-String"), which is either const wchar_t* or const char* depending on the character set. So just pass in a string surrounded by _T(), me gusta:

CreateFile(_T("C:\\File.txt"), FILE_READ_DATA, FILE_SHARE_READ,
    NULL, OPEN_ALWAYS, 0, NULL);

(Por cierto, FILE is not part of the Windows SDK; it's part of the standard C runtime library, and it's internally basado on CreateFile, which creates a file based on its name.)

Respondido el 09 de enero de 11 a las 10:01

can you name the header file for _T please. I have included <windows.h> and <stdio.h>. but it's showing _T is undefined. - narayanpatra

Thanks buddy , it's done. I was too lazy. Thanks for your help. - narayanpatra

Sure, no problem. Fun fact: the TEXT() macro does the same thing, but it's just defined in a different header file... feel free to use that instead, if you want. :) - user541686

Problem has not solved. The code is running without error but There is no file created in C drive. I tried with both _T and TEXT(). - narayanpatra

@narayanpatra: Did you check the return value from CreateFile? If it returned either NULL or INVALID_HANDLE_VALUE, deberías llamar GetLastError to find out why. Do you have permission to write to the directory? Using the Win32 API doesn't bypass permission checks. - Ben Voigt

Pasa el nombre of the file. A string. Use the SDK código de ejemplo.

Respondido el 07 de diciembre de 18 a las 21:12

In that example , file name is passed by command line. I want to hard code it in my code. - narayanpatra

To create file with CreateFile() función:

CreateFile("OUTPUT_FILE", GENERIC_WRITE, 0, NULL,
CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);

The first parameter is the name of the file which you can pass from any string variable..for example if the filename is in CString variable you can pass (LPCTSTR) variblename to convert it to LPCTSTR. all the other parameters are depending on your implementation whether you want to create the file always or append to existing file etc...

Respondido 01 ago 18, 09:08

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.