Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 472
  • Last Modified:

CreateFile fails in VS2005

If I create a test MFC dialog app. in VS2005 and in the OnInitDialog() generated code I add the following code just before the return:
DWORD d;
HANDLE h;
SetLastError(0);
h = CreateFile((LPCTSTR)"C:\\document.rtf",FILE_READ_EA,FILE_SHARE_READ,NULL,OPEN_EXISTING,NULL,NULL);
d = GetLastError();

CreateFile fails with d=2.  If I create a the same app. in VC++6 it works fine.  What gives?
0
Taurus
Asked:
Taurus
  • 2
1 Solution
 
manish_regmiCommented:
error 2 means: The system cannot find the file specified.

It means the file does not exist.

Also you don't need a type cast.

regards
Manish Regmi
0
 
manish_regmiCommented:
if you want to create new if the file does not exist use

OPEN_ALWAYS

CreateFile(path, // drive to open
                       GENERIC_READ | GENERIC_WRITE,    
                       FILE_SHARE_READ | FILE_SHARE_WRITE,  // share mode
                       NULL,    // default security attributes
                       OPEN_ALWAYS,  // disposition
                       0,       // file attributes
                       NULL);   // don't copy any file's attributes

regards
Manish Regmi
0
 
AlexFMCommented:
h = CreateFile(_T("C:\\document.rtf"),FILE_READ_EA,FILE_SHARE_READ,NULL,OPEN_EXISTING,NULL,NULL);

Add _T macro. VC++ creates Unicode application by default, your ANSI string is casted to Unicode string, which gives incorrect result. This also shows that using type casting without reason is dangerous: instead of compilation error you have runtime error.
0
 
TaurusAuthor Commented:
I had forgotten about _T, and you are absolutely correct about using typecasting without reason.  Thanks.
0

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now