Date: 2009oct5
Platform: win32
Language: C/C++
Keywords: fopen, OpenFile, simple
Q. How can I use CreateFile() to simply open a file for reading?
A.
HANDLE OpenForRead(LPCTSTR szSrc)
{
HANDLE h = CreateFile(szSrc // name of the file
,GENERIC_READ // access mode
,FILE_SHARE_READ // Share mode
,NULL // Security
,OPEN_EXISTING // how to create
,FILE_ATTRIBUTE_NORMAL // file attributes
,NULL); // Template
if (h == INVALID_HANDLE_VALUE) h = NULL;
return h;
}
This is the the same as:
FILE *OpenForReadStd(LPCSTR szSrc)
{
return fopen(szSrc, "rb");
}
Except you get a different kind of handle.
void ExampleUse()
{
LPCSTR szSrc = "c:\\myfile.txt";
HANDLE h;
if ((h = OpenForRead(szSrc)) == NULL)
{
// ... Problem ...
return;
}
// ... Read from the handle...
CloseHandle(h);
}