INF: Opening Files from a Shared Library

ID Number: Q29962

3.00

WINDOWS

Summary:

In Chapter 19 of "Programming Windows" by Charles Petzold are DLL

examples of creating and opening an MS-DOS file from within a shared

library. The following program uses a DLL library to accept and store

strings in a sorted array. When added to the STRLIB.C source, this

program will quickly move the strings to a file.

More Information:

Some changes are needed in other files to make this program work. For

example, export the SaveStrings function in the STRLIB.DEF, import the

function in the STRPROG.DEF, and use it in the STRPROG.C.

Please note that since this is a rather terse example, extra error-

checking and recovery operations should be done in a "real"

application.

The following is an example of the program:

HANDLE hFile;

BOOL FAR PASCAL SaveStrings (lpFileName)

LPSTR lpFileName;

{

OFSTRUCT reOpenBuff;

WORD wStyle;

int strLength, wriLength, i;

NPSTR npString;

hFile = OpenFile (lpFileName, &reOpenBuff, OF_CREATE | OF_WRITE);

/* you should check hFile for success */

for (i = 0; i < nTotal; i++) {

npString = LocalLock (hStrings [i]) ;

strLength = lstrlen ((LPSTR)npString);

wriLength = _lwrite (hFile, (LPSTR)npString, strLength);

if (wriLength == strLength) {

_lwrite (hFile, "\r\n", 2);

} else {

/* something went wrong, handle it here */

}

LocalUnlock (hStrings [i]) ;

}

_lclose (hFile);

return TRUE;

}

Note: The file handle retrieved from the OpenFile function will be

valid only for the application that called the DLL for that particular

OpenFile, since the DLL has no File Handle Table of its own.

Therefore, two applications cannot write to a file using the same file

handle as a reference. (Although the file handle may be the same

value, it does not reference the same File Handle Table.) The file

must be opened by a call from the application that wants to use the

file in order for a valid file handle to be generated for that

application.