On Fri, 25 Dec 1998, Nuno Carvalho wrote:

> Hi,
> 
>  Is there some way to open a file with fopen() on mode "r+b" but if the
> file doesn't exist it create a new one automatically !?
> 
>  I only can do it with "a+b" but I don't want the append command !

If you don't want to truncate an existing file use something 
along the lines of:

/* ANSI C */
char *MYFILE="./somefile";
FILE *foo;
if( NULL == (foo=fopen(MYFILE, "r+")) )
        {
        if( NULL == (foo=fopen(MYFILE, "w+")) )
                {
                fprintf(stderr, "Couldn't open file:%s\n",MYFILE);
                return -1;
                }
        }

The stream is at the beginning of the file in both cases. If
you want to truncate a file if it exists, or create it if it 
does not exist then use fopen(MYFILE, "w+"). It is all covered 
in the fopen man page.

I suspect that you don't know the ANSI C functions very
well, as your question is basic ANSI C. If this is true 
then you should start reading up on:

       int fseek( FILE *stream, long offset, int whence);
       long ftell( FILE *stream);
       void rewind( FILE *stream);
       int fgetpos( FILE *stream, fpos_t *pos);
       int fsetpos( FILE *stream, fpos_t *pos);

and you will be enlightened.



Reply via email to