smishr4
smishr4

Reputation: 45

CreateFile function in Visual C++

I want to use CreateFile() function in Visual C++. when I am using it in this way:-

{
BOOL bTest=FALSE;
DWORD dwNumRead=0;
HANDLE hFile=CreateFile(L"D:\\a.dat",GENERIC_READ,FILE_SHARE_READ,
                              NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL,NULL);
bTest= CloseHandle(hFile);
}

The value of bTest is coming out to be False and the file is not created. Please, if possible, illustrate an example to create a file using CreateFile and tell me what I am doing wrong.

Upvotes: 1

Views: 37015

Answers (3)

Jeeva
Jeeva

Reputation: 4663

The actual problem is you are getting an Invalid File Handle in CreateFile function because of the parameter dwCreationDisposition where you specify OPEN_EXISTING. It means that Opens a file or device, only if it exists. Change it to CREATE_ALWAYS or CREATE_NEW it will work.

Upvotes: 1

user1373630
user1373630

Reputation: 63

If you wish to create a file use CREATE_ALWAYS or CREATE_NEW instead of OPEN_EXISTING.

CreateFile function http://msdn.microsoft.com/en-us/library/windows/desktop/aa363858%28v=vs.85%29.aspx

Upvotes: 2

MSalters
MSalters

Reputation: 179917

"OPEN_EXISTING : Opens a file or device, only if it exists. If the specified file or device does not exist, the function fails". That's your problem, I bet.

GetLastError() would tell you more, though.

Upvotes: 1

Related Questions