CreateFile(), GetHandleInformation() and CloseHandle()

 

 

Compiler: Visual C++ Express Edition 2005

Compiled on Platform: Windows XP Pro SP2

Header file: Standard and Windows

Additional library: Windows Platform SDK

Additional project setting: Set project to be compiled as C

Project -> your_project_name Properties -> Configuration Properties -> C/C++ -> Advanced -> Compiled As: Compiled as C Code (/TC)

Other info: non-CLR or unmanaged

To do: Using file handle

To show: File handle: CreateFile(), GetHandleInformation() and CloseHandle()

 

// File handle: CreateFile(), GetHandleInformation() and CloseHandle()

#include <windows.h>

#include <stdio.h>

 

int main(void)

{

// handle to a file

HANDLE hFile;

// file and path, change accordingly. LPCWSTR is a pointer to a constant

// null-terminated string of 16-bit Unicode characters. It is a typedef:

// typedef CONST WCHAR *LPCWSTR. The modifier 'L' is for wide character.

LPCWSTR fname = L"c:\\testfile.txt";

DWORD lpdwFlags[100];

BOOL test;

 

// Create a file with the given information...

hFile = CreateFile(fname, // file to be opened

GENERIC_WRITE, // open for writing

FILE_SHARE_WRITE, // share for writing

NULL, // default security

CREATE_ALWAYS, // create new file only

FILE_ATTRIBUTE_NORMAL |FILE_ATTRIBUTE_ARCHIVE | SECURITY_IMPERSONATION,

// normal file archive and impersonate client

NULL); // no attr. template

 

if(hFile == INVALID_HANDLE_VALUE)

printf("Could not open %s file, error %d\n", fname, GetLastError());

else

{

printf("File's HANDLE is OK!\n");

test = GetHandleInformation(hFile, lpdwFlags);

printf("The return value is %d, error %d\n", test, GetLastError());

}

// when finished, close the file handle

CloseHandle(hFile);

DeleteFile(fname);

return 0;

}

 

Output example:

 

File's HANDLE is OK!

The return value is 1, error 0

Press any key to continue . . .

 

 

C and C++ Programming Resources | C & C++ Code Example Index