Creating Files

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

A null-terminated filename for the file you're creating

A buffer with the type OFSTRUCT

The OF_CREATE option

The following example creates the FILE.TXT file and returns a handle to 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 */