CreateFile(), GetFileType(), GetFileSize(), 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: More on file management
To show: Using CreateFile(), GetFileType(), GetFileSize(), CloseHandle() C functions
#include <windows.h>
#include <stdio.h>
int main(void)
{
// the files' handles
HANDLE hFile, hFile1;
// filenames, the file is not there...
LPCWSTR fname = L"c:\\test.doc";
// the file is there...
LPCWSTR fname1 = L"c:\\txtcode\\module11.txt";
// temporary storage for file sizes
DWORD dwFileSize;
DWORD dwFileType;
// Create the test file. Open it "Create Always" to overwrite any existing file...
hFile = CreateFile(fname, GENERIC_READ | GENERIC_WRITE, 0, NULL,
CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if(hFile == INVALID_HANDLE_VALUE)
{
printf("hFile is NULL\n");
printf("Could not create %S\n", fname);
// return error
return 4;
}
else
printf("%S file was created successfully!\n", fname);
// Get the file type...
dwFileType = GetFileType(hFile);
// Verify that the correct file size was written.
dwFileSize = GetFileSize(hFile, NULL);
printf("%S size is %d bytes and file type is %d\n", fname, dwFileSize, dwFileType);
CloseHandle(hFile); // close the file handle and the file itself
// Opening the existing file
hFile1 = CreateFile(fname1, // file to open
GENERIC_READ, // open for reading
FILE_SHARE_READ, // share for reading
NULL, // default security
OPEN_EXISTING, // existing file only
FILE_ATTRIBUTE_NORMAL,// normal file
NULL); // no attribute template
if(hFile1 == INVALID_HANDLE_VALUE)
{
printf("Could not open %S file, error %d\n", fname1, GetLastError());
return 1;
}
dwFileType = GetFileType(hFile1);
dwFileSize = GetFileSize(hFile1, NULL);
printf("%S size is %d bytes and file type is %d\n", fname1, dwFileSize, dwFileType);
// close the file's handle and itself
CloseHandle(hFile1);
return 0;
}
Output example:
c:\test.doc file was created successfully!
c:\test.doc size is 0 bytes and file type is 1
c:\txtcode\module11.txt size is 13550 bytes and file type is 1
Press any key to continue . . .