CreateFile(), GetFileType(), GetBinaryType(), 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: Checking a file type
To show: Using CreateFile(), GetFileType(), GetBinaryType(), CloseHandle() C functions
#include <windows.h>
#include <stdio.h>
int main(void)
{
// handle for file
HANDLE hFile;
DWORD lpBinaryType[100];
// file and path, make sure the file is there...
LPCWSTR fname = L"c:\\test.doc";
// Windows XP PRo, change accordingly, the file is there
LPCWSTR fname2 = L"c:\\windows\\NOTEPAD.EXE";
hFile = CreateFile(fname, //file to be opened
GENERIC_READ, //open for reading
FILE_SHARE_READ, //share for reading
NULL, //default security
OPEN_EXISTING, //open existing file
FILE_ATTRIBUTE_READONLY, //the file is read only
NULL); //no attribute template
if(hFile == INVALID_HANDLE_VALUE)
printf("Could not open %s file, error %d\n", fname, GetLastError());
else
printf("%S file opened successfully.\n", fname);
printf("File's HANDLE is OK!\n");
if(GetFileType(hFile) == 0)
printf("The %S file is character type.\n", fname);
else if (GetFileType(hFile) == 1)
printf("The %S file is disk file.\n", fname);
else if (GetFileType(hFile) == 2)
printf("The %S file is socket or named pipe.\n", fname);
else if (GetFileType(hFile) == 4)
printf("The %S file is UNKNOWN type or GetFileType() failed!\n", fname);
CloseHandle(hFile);
if(GetBinaryType(fname2, lpBinaryType) != 0)
printf("The %S file is executable.\n", fname2);
else
printf("The %S is file non-executable.\n", fname2);
return 0;
}
Output example:
c:\test.doc file opened successfully.
File's HANDLE is OK!
The c:\test.doc file is disk file.
The c:\windows\NOTEPAD.EXE file is executable.
Press any key to continue . . .