Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

c

windows

fopen

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?

like image 692
Zain Rizvi Avatar asked Jan 18 '11 20:01

Zain Rizvi


People also ask

Does fopen create a new file in C?

The fopen function creates the file if it does not exist.

What is fopen rb in C?

The fopen() function opens a file indicated by fname and returns a stream associated with that file. If there is an error, fopen() returns NULL. mode is used to determine how the file will be treated (i.e. for input, output, etc) Mode.

What is r in fopen?

r or rb. Open file for reading. w or wb. Truncate to zero length or create file for writing.

What does fopen return if successful?

Returned value If successful, fopen() returns a pointer to the object controlling the associated stream. If unsuccessful, fopen() returns a NULL pointer.


3 Answers

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

like image 119
rerun Avatar answered Oct 31 '22 10:10

rerun


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).

like image 22
Bill Forster Avatar answered Oct 31 '22 11:10

Bill Forster


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.

like image 34
baris.aydinoz Avatar answered Oct 31 '22 10:10

baris.aydinoz