Dave's Brain

Browse - Programming Tips - How can I use CreateFile() to simply open a file for reading?

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); }

Add a comment

Sign in to add a comment
Copyright © 2008-2017, dave - Code samples on Dave's Brain is licensed under the Creative Commons Attribution 2.5 License. However other material, including English text has all rights reserved.