Creating file in C drive

I am having trouble creating a file on the C drive. I wrote the code below to troubleshoot the problem. It is based on the code from the tutorial section on input/output with files. The test for whether the file is open always fails. If I replace the C: with H: (which is a USB flash drive), the file is successfully created and written to. I searched the archives by "file path" but there were over 4000 entries; the few that I read provided no clues. I cannot understand what it is about the C drive that won't create the file. I am using the Codeblocks 13.12 IDE under Windows 10. Thanks in advance.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
#include <fstream>

using namespace std;

int main()
{
   fstream myfile1;
   myfile1.open("C:/example2.txt", ios::out);

   if (myfile1.is_open())
   {
     myfile1 << "Add this text. \n";
     myfile1 << "Add More text .\n";
     cout << "File created. \n";
   }
   else
   {
      cout << "Unable to open file. \n";
   }
   myfile1.close();
   return 0;

}
The root of your C: drive probably has special permissions associated with it.

If you right-click on your C: drive, and go to Security, you'll probably see that the Authenticated Users group doesn't have access by default.

I would just make a subfolder within C:\ (e.g. C:\code) and write within that.
Or, run your program as an Administrator (elevated context).
Or, give yourself write permissions to C:\

PS: I dislike programs that clutter up the root of C: so my opinion would be my first suggestion is the best.
Last edited on
Yes, it's normal for the root directory of the C: drive to be write-protected. That directory contains files and directories that are essential for Windows to function, so it's important to put barriers in the way of people doing things that might cause their computer to stop working.

As Ganado says, put the files in a subdirectory that you own and have permission to write to.
Thank you, gentlemen for clearing this up. I have marked this as solved.
Topic archived. No new replies allowed.