5

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

blunatic
  • 325
  • 2
  • 6
  • 16

1 Answers1

4

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;
Nostromoo
  • 284
  • 1
  • 5
  • Using `_open` with `_O_EXCL` and then [`_fdopen`](http://msdn.microsoft.com/en-us/library/dye30d82.aspx) should be fine... That way the standard file output functions can be used still instead of the `_write` primitive. –  Oct 25 '14 at 14:06