CreateDirectory(), CreateFile(), CloseHandle(), DeleteFile(), RemoveDirectory()

 

 

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: Create directory and file then remove them

To show: Using CreateDirectory(), CreateFile(), CloseHandle(), DeleteFile(), RemoveDirectory() C functions

 

 

#include <windows.h>

#include <stdio.h>

 

int main(void)

{

LPCWSTR szDirPath = L"c:\\testdir";

HANDLE hFile;

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

 

// Create a new directory.

if(!CreateDirectory(szDirPath, NULL))

printf("\nCouldn't create %S directory.\n", szDirPath);

else

printf("\n%S directory successfully created.\n", szDirPath);

 

// Create a file

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

GENERIC_READ, //open for writing

FILE_SHARE_READ, //share for writing

NULL, //default security

CREATE_ALWAYS, //create new file only

FILE_ATTRIBUTE_ARCHIVE | SECURITY_IMPERSONATION,

//archive and impersonate client

NULL); //no attribute template

 

// Check the handle, then open...

if(hFile == INVALID_HANDLE_VALUE)

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

else

{

printf("\n%S file HANDLE is OK!\n", fname);

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

}

 

// Close the handle...

if(CloseHandle(hFile) != 0)

printf("\nCloseHandle() for %S file succeeded!\n", fname);

else

printf("\nCloseHandle() for %S file failed!\n", fname);

 

if(DeleteFile(fname) != 0)

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

else

printf("\n%S file deletion failed!\n", fname);

 

// Delete the directory...

if(RemoveDirectory(szDirPath) != 0)

printf("\n%S directory successfully deleted.\n", szDirPath);

else

printf("\n%S directory deletion failed.\n", szDirPath);

return 0;

}

 

Output example:

 

c:\testdir directory successfully created.

c:\testdir\testfile.txt file HANDLE is OK!

c:\testdir\testfile.txt opened successfully!

CloseHandle() for c:\testdir\testfile.txt file succeeded!

c:\testdir\testfile.txt file successfully deleted!

c:\testdir directory successfully deleted.

Press any key to continue . . .

 

 

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