File handle, attributes: CreateFile(), CloseHandle() and DeleteFile()


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 a file handle

To show: How to use file handles and attributes: CreateFile(), CloseHandle() and DeleteFile()




// File handles and attributes example: CreateFile(), CloseHandle() and DeleteFile()

#include <windows.h>

#include <stdio.h>


int main(void)


// handle for file


// file and path, the file is exist at the location

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


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


// normal file archive and impersonate client

NULL); // no attribute template



// Notice the use of capital %S specifier...

// When used with printf() functions, specifies a wide-character string

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



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

printf("%S opened successfully!\n", fname);



if(CloseHandle(hFile) != 0)

printf("CloseHandle() succeeded!\n");


if(DeleteFile(fname) != 0)

printf("%S file successfully deleted!\n", fname);

return 0;



Output example:


File's HANDLE is OK!

c:\mytestfile.txt opened successfully!

CloseHandle() succeeded!

c:\mytestfile.txt file successfully deleted!

Press any key to continue . . .



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