gpt4 book ai didi

CreateFile() 成功,但文件不在磁盘上。

转载 作者:行者123 更新时间:2023-11-30 15:26:20 31 4
gpt4 key购买 nike

HANDLE hFile = CreateFile(LPCTSTR("filename"),          // name of the write
GENERIC_READ | GENERIC_WRITE, // open for writing and reading
0, // do not share
NULL, // default security
OPEN_ALWAYS, // create new file only
FILE_ATTRIBUTE_NORMAL, // normal file
NULL);
if(hFile != INVALID_HANDLE_VALUE)
{
printf("Success.\n");
}

CloseHandle(hFile);

操作成功,但我在磁盘上找不到“文件名”。CreateFile()实际上在磁盘上创建文件吗?

最佳答案

我尝试了一个仅包含您的代码的最小程序,并且...该文件已在当前目录中正确创建!但前提是程序以 ANSI 模式编译,因为 LPCTSTR 只将指针转换为 LPCTSTR,而不会从 ANSI 转换为 UNICODE。只有 _T 宏可以做到这一点。

您应该使用 GetCurrentDirectory 来控制尝试写入文件的位置,并使用 TCHAR 与 UNICODE 兼容:

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

int main() {
LPTSTR dir;
DWORD cr = ::GetCurrentDirectory(0, NULL);
cr += 1;
dir = (LPTSTR) malloc(cr * sizeof(TCHAR));
cr = ::GetCurrentDirectory(cr, dir);

/* ::MessageBox(NULL, dir, _T("Current dir"), MB_OK); */
_tprintf(_T("Current dir : %s\n"), dir); // note the _tprintf and _T macro
free(dir);

HANDLE hFile = CreateFile(_T("filename"), // name of the write - _T
GENERIC_READ | GENERIC_WRITE, // open for writing and reading
0, // do not share
NULL, // default security
OPEN_ALWAYS, // create new file only
FILE_ATTRIBUTE_NORMAL, // normal file
NULL);
if(hFile != INVALID_HANDLE_VALUE)
{
printf("Success.\n");
}

CloseHandle(hFile);
return 0;
}

如果我在 UNICODE 模式下编译,而 "filename" 周围没有 _T 宏,则程序确实会创建一个文件,但其名称只是垃圾

关于CreateFile() 成功,但文件不在磁盘上。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27401282/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com