Dave's Brain

Browse - programming tips - win32 simple use of createfile to open a file for reading

Date: 2009oct5
Platform: win32
Language: C/C++

Q.  How can I use CreateFile() to simply open a file for reading?

A.

inline HANDLE OpenForRead(LPCTSTR szSrc)
{
	HANDLE		h;

	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:

inline 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);
}
What this info useful to you? You can donate to say thanks

Add a comment

Sign in to add a comment
Copyright © 2008-2010, 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.