1

I am unable to create file in C:\ Drive using fopen() due to permission issue,is there any way by which I am able to create file in C drive. I am using Visual studio 2005. Here is the code:

int main()
{
    std::string abc = "C:\\test.txt";
    FILE* fp=NULL;
    fp= fopen(abc.c_str(), "wt");
    if(fp != NULL)
    {
        printf("Success");
        fclose(fp);
    }
    else
        printf("Fail");
    getch();
    return 0;
}  
Paul R
  • 208,748
  • 37
  • 389
  • 560
  • you just go to C drive and right click on free space and try to create a new file by manually. Then you can check whether ou have permission to write into C drive or not – MeshBoy Mar 27 '15 at 06:55
  • yep, you'd better not create file on C Driver root directory, because ,maybe your application dont have the right permission . – wshcdr Mar 27 '15 at 06:57
  • I have created a file test.txt in the C drive, but still i am not able to write it. – Kuldeep Kumar Mar 27 '15 at 07:51
  • If i will run my application in admin mode i am able to create it and write it, But is there any way by which i can create and write file in C drive without running application in admin mode. – Kuldeep Kumar Mar 27 '15 at 07:54
  • Generally when a user (and thus your applications run with that user's credentials) is denied access to do something, the intention is to prevent that thing from being done. "Getting around it" would basically make it worthless in the first place. (That being said, I don't know whether or not there is some way.) – zenzelezz Mar 27 '15 at 08:20

3 Answers3

2

No, in all current versions of Windows only administrators are permitted to put files in the root directory of the C drive. You will need to either run the program as an administrator, or put the file in a more appropriate location.

Older versions of Windows (perhaps as recently as Windows 2000?) did allow this. I believe that the main reason for the change was that many programs have elevation of privilege vulnerabilities that can be exploited by malicious files placed in the root directory.

Harry Johnston
  • 35,639
  • 6
  • 68
  • 158
1

Just make a folder with any name like 'test' in C drive and then call fopen() for that directory. Also that you should try running your program as administrator. If you are using any IDE then start that IDE as administrator and try running your program. That will solve your problem

Yasir Majeed
  • 739
  • 3
  • 12
1

One of the main reasons could be that you didn't opened VS (Visual studio) as an admin.

Also, I'd suggest using ofstream rather then FILE. Of course, using ofstream is better for the main reason which is the RAII.

Hope that helps you.

Community
  • 1
  • 1
OhadM
  • 4,687
  • 1
  • 47
  • 57