由CreateFile()函数创build的文本文件不显示

我想打开一个文本文件。 如果该文件不存在,则必须先创build并打开该文件。 我已经为此写了下面这段代码。 代码工作正常,它也创buildBIN文件夹内的文件,但我仍然看不到任何文件打开时,我exexute代码。 请告诉我的代码有什么问题。

代码片段:

#include "stdafx.h" #include <windows.h> #include <iostream> #include <string> using namespace std; int WINAPI WinMain( HINSTANCE hInst, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd ) { HANDLE hFile; DWORD dwBytesRead, dwBytesWritten, dwPos; TCHAR szMsg[1000]; hFile = CreateFile (("File.txt"), // Open File.txt. GENERIC_WRITE, // Open for writing 0, // Do not share NULL, // No security OPEN_ALWAYS, // Open or create FILE_ATTRIBUTE_NORMAL, // Normal file NULL); // No template file if (hFile == INVALID_HANDLE_VALUE) { wsprintf (szMsg, TEXT("Could not open File.txt")); CloseHandle (hFile); // Close the file. return 0; } return 0; } 

我以为CREATE_FILE()的参数“OPEN_ALWAYS”会打开我前面的文本文件

不,它实际上不会在你面前打开文件,就像你在资源管理器中双击它一样。

相反, OPEN_ALWAYS参数意味着打开文件句柄 ,例如,可以通过编程方式读取或写入。 如果指定OPEN_ALWAYS ,则CreateFile函数将成功创建文件并打开该文件的句柄,即使文件已经存在。

如果你想要这种行为,你可以指定OPEN_EXISTING ,只有在文件(或设备)已经存在的情况下才能打开一个句柄。 如果它不存在, CreateFile函数将返回一个错误。

请记住,正如其他人所指出的那样,您需要通过调用CloseHandle来成功调用CreateFile 。 这可以确保您已经打开文件(或设备)的句柄被正确释放,并防止应用程序泄漏资源。 但是,如果对CreateFile的调用成功,则只需执行此操作。 如果失败,则返回INVALID_HANDLE_VALUE ,那么不应该为该句柄调用CloseHandle

 int WINAPI WinMain(HINSTANCE hInst, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd) { HANDLE hFile; DWORD dwBytesRead, dwBytesWritten, dwPos; TCHAR szMsg[1000]; // If the file already exists, open a handle to it for writing. // If the file does not exist, create it and then open a handle to it. hFile = CreateFile(TEXT("File.txt"), // Open File.txt. GENERIC_WRITE, // Open for writing 0, // Do not share NULL, // No security OPEN_ALWAYS, // Open or create FILE_ATTRIBUTE_NORMAL, // Normal file NULL); // No template file // Test for and handle failure... if (hFile == INVALID_HANDLE_VALUE) { wsprintf(szMsg, TEXT("Could not open File.txt")); MessageBox(NULL, szMsg, NULL, MB_OK | MB_ICONERROR); // don't close the file here because it wasn't opened! return 0; } // Read from, write to, or otherwise modify the file here, // using the hFile handle. // // For example, you might call the WriteFile function. // ... // Once we're finished, close the handle to the file and exit. CloseHandle (hFile); // Close the file. return 0; } 

MSDN上有一个完整的示例: 打开一个文件进行阅读或写作

如果您想打开文本文件,就好像您在资源管理器中双击它一样,您需要使用ShellExecute函数 。 它不需要处理文件,只需要路径。 自然, open动词是你想指定的。 请注意,当您尝试使用ShellExecute打开文件时,不应该有该文件的打开句柄。 如果您使用CreateFile打开/创建了该文件,请确保调用ShellExecute 之前调用CloseHandle

首先,如果hFileINVALID_HANDLE_VALUE ,则不需要调用CloseHandle 。 删除该语句。 另外,如果你在返回之前CloseHandle会更好,因为释放你使用的任何资源总是很好的。 如果您将此代码复制到一个函数和一个称为该函数的巨大应用程序,您将有资源泄漏。