10.3 Creating a File

To create a new file, use the OpenFile function. When you call OpenFile, you specify the following:

A null-terminated filename for the file

A buffer with the type OFSTRUCT

The OF_CREATE option

The following example creates the FILE.TXT file and returns a handle of the file. The application can then use this file handle with low-level, C run-time I/O functions.

int hFile;
OFSTRUCT OfStruct;
        .
        .
        .

hFile = OpenFile("FILE.TXT", &OfStruct, OF_CREATE);

The OpenFile function creates the file, if necessary, and opens it for writing. If the file already exists, the function truncates it to zero length and opens it for writing.

If you want to avoid overwriting an existing file, you can check whether the file exists, before creating a new file, by calling OpenFile as follows:

hFile = OpenFile("FILE.TXT", &OfStruct, OF_EXIST);
if (hFile >= 0) {
    wAction = MessageBox(hWnd,
        (LPSTR) "File exists. Overwrite?",
        (LPSTR) "File",
        MB_OKCANCEL);
    if (wAction == IDCANCEL)

/* End this processing. */

    }
}

/* Open the file. */