如何使用 Windows API 创建文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4638143/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 15:56:35  来源:igfitidea点击:

how to create a file using windows API?

cwindowswinapivisual-c++file

提问by narayanpatra

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

我想使用 Windows API 创建一个文本文件。我研究了

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.

我无法理解如何传递第一个参数来创建文件。我尝试使用数据类型 FILE 并将其指针作为第一个参数传递,但它显示与 LPCTSTR 不兼容。谁能告诉我怎么做?我是使用 Windows API 的新手。提前致谢。

回答by user541686

LPCTSTRis the same as 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(), like:

LPCTSTR是相同的const TCHAR*(“长指针到恒定TCHAR-string”),其是const wchar_t*const char*取决于字符集。因此,只需传入一个由 包围的字符串_T(),例如:

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

(By the way, FILEis not part of the Windows SDK; it's part of the standard C runtime library, and it's internally basedon CreateFile, which creates a file based on its name.)

(顺便说一下,FILE是不是Windows SDK的一部分;它是标准的C运行时库的一部分,它的内部基础CreateFile,基于它的名字它创建了一个文件。)

回答by Hans Passant

Pass the nameof the file. A string. Use the SDK example code.

的文件。一个字符串。使用 SDK示例代码

回答by programmer

To create file with CreateFile()function :

使用CreateFile()函数创建文件:

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...

第一个参数是您可以从任何字符串变量传递的文件名。例如,如果文件名在 CString 变量中,您可以传递 (LPCTSTR) 变量名将其转换为 LPCTSTR。所有其他参数都取决于您的实现是要始终创建文件还是附加到现有文件等...