Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alternative to fopen()'s mode "wx" for Windows fopen()?

I've got a basic program that's designed to copy the functionality of bash's cp command. I'm developing a copy for UNIX and for Windows. My UNIX version works fine, however, I'm finding that Windows doesn't have support for the "wx" mode option for fopen(), as in the following line:

file2 = fopen(argv[2], "wx");

Is there an alternative way to mirror the wx functionality mode for fopen here?

(wx allows for opening a file with write access, but will return an error if a file with the same filename already exists--meaning you won't override the existing file. See here.

note: attempting to run the program in Developer Command Prompt for VS2013

like image 929
blunatic Avatar asked Oct 20 '22 14:10

blunatic


1 Answers

The short answer is that you cannot pass "wx" or any equivalent to fopen that will yield a CreateFile with CREATE_NEW. fopen simply does not accept any parameter combination to yield that - it's very limited. You can see the source code yourself for fopen in the Visual Studio CRT code base!

However you can instead call CreateFile directly. This is probably the best approach.

Alternatively you can call _open (http://msdn.microsoft.com/en-us/library/z0kc8e3z.aspx) which will take the parameter _O_EXCL which can yield CREATE_NEW and thus will cause it to fail if the file exists as you want.

From the CRT:

case _O_CREAT | _O_EXCL:
case _O_CREAT | _O_TRUNC | _O_EXCL:
    filecreate = CREATE_NEW;
    break;
like image 164
Nostromoo Avatar answered Oct 23 '22 07:10

Nostromoo