Zain Rizvi
Zain Rizvi

Reputation: 24656

fopen fails invisibly when creating files in system drive (C:\)

Whenever I try to create a file using fopen, fopen acts as if the file has been opened properly and that it has full access to it, but it doesn't actually create the file. My program doesn't have write access to the system root folder because it needs admin access to write there, but why isn't fopen() giving any errors?

Any idea how to tell if there's an error or not? The file handle that gets returned when I'm trying to open the file in a protected directory is exactly the same as when I open a file in a directory where I have write access.

I've tried this with the various different versions of fopen (fopen, _wfopen, _wfopen_s) but they all have the same output.

Interestingly enough, GetLastError() returns ERROR_ALREADY_EXISTS.

Here's the code that I'm using:

FILE *FileHandle; 
DWORD error = _wfopen_s(&FileHandle, L"\\filename.txt", L"a");
Win32Error = GetLastError();

if (error != 0 || FileHandle == NULL)
{
    //Throw error
}
else 
{
    //write to file
    //close file
}

EDIT: As rerun pointed out, the file is getting created in %APPDATA% because of virtualization. Does anyone know how to disable this feature?

Upvotes: 5

Views: 2587

Answers (3)

baris.aydinoz
baris.aydinoz

Reputation: 1950

We had a similar problem in registry virtualization, yes it is also virtualized after Vista.

Our solution was Properties->Linker->Manifest File->UAC Execution Level-> requireAdministrator. IMHO, It may work for your case also.

Upvotes: 3

Bill Forster
Bill Forster

Reputation: 6297

If you are literally running the code you posted, then you aren't asking for a file in the root directory at all. You need to go "c:\\filename.txt" (two '\' characters) instead. Maybe if you look in the current directory you'll find you've successfully created a weirdly named file (basically <formfeed>ilename.txt, I think).

Upvotes: 3

rerun
rerun

Reputation: 25505

This might have to do with the virtual store. Take a look here for some info.

Upvotes: 6

Related Questions