Programming question

Ben Pfaff pfaffben@msu.edu
21 Jan 2001 04:17:20 -0500


"Don Chorman" <chormand@pilot.msu.edu> writes:

> I am writing a program in C++, and I need it to write to
> a new file. I'm know how to do this part, but I want to 
> avoid overwriting files, or atleast warn the user that a 
> particular file exists. Can I code this in C++?

I will suppose that you are using the C stream input/output
functions (fopen, fclose, ...).  With this assumption, one answer
is "no, not within standard ANSI C."  However, you have several
options besides standard ANSI C:

	1. You can stat() the file or try to open it for reading
           or whatever, but all solutions of this type are
           subject to a race condition.

	2. You can use mode "wx" when opening the file.  This
           will fail the open if it would clobber an existing
           file.  This will only work with GNU libc.

	3. You can use open() with O_EXCL to open the file, then
           fdopen() to get a stream for it.  This works on all
           POSIX systems.  This is probably the best choice.

> Can I run shell scripts within a C++ program?

#include <stdlib.h>

system ("/shell/script/name");

> I ask because I see scripts doing a similar checks, and
> I could use that code as an example to go by.

Probably a bad choice--I bet those scripts are riddled with
races.