-2

i wrote some code to createfile in c++ it compiles without errors, but it doesn't create any file.. Can anyone tell me what is wrong ? thanks

#include <iostream>
#include <windows.h>
#include <string>
using namespace std;

    int main()
    {
        HANDLE hfile;
        char data[] = "some text to write into file";       

        hfile = CreateFile(
               L"c:\name.txt",              
               GENERIC_WRITE, 
               0,
               NULL,
               CREATE_NEW,
               FILE_ATTRIBUTE_NORMAL,
               NULL);

        /*
        if (hFile == INVALID_HANDLE_VALUE) 
        { 
            cout << "Unable to create file \n";

        }
        */
    return 0;
    }
CharlesB
  • 86,532
  • 28
  • 194
  • 218
asdf
  • 55
  • 1
  • 1
  • 2

2 Answers2

4

Also in C++ you need to escape the backslash, i.e.

"C:\\mydirectory\\"...
John Lockwood
  • 3,787
  • 29
  • 27
2

If trying to create it into the root, you may run into a permissions issue if not logged in as administrator. Try creating it in a subdirectory.

John Lockwood
  • 3,787
  • 29
  • 27
  • I'm administrator :) I also have tried this hfile = CreateFile( L"C:\Users\Vardan\Desktop\name.txt", GENERIC_WRITE, 0, NULL, CREATE_NEW, FILE_ATTRIBUTE_NORMAL, NULL); but it didn't create any file – asdf Sep 22 '12 at 19:09
  • Being administrator and running the executable AS administrator are two different things. But my other answer is more to the point -- square that away then try it in a subdirectory and you should get some joy. (One way to ensure you're running as administrator is right click on the file in explorer, then "run as administrator"). – John Lockwood Sep 22 '12 at 19:13