Locking a file

Code found in an e-mail to Peg, send by by Jeffrey L. Boyer

Sometimes you want to read a file and be sure that nobody else is writing to the file in the meantime. So you want to lock it for writing.

&GLOBAL-DEFINE GENERIC_WRITE 1073741824   /* &H40000000 */
&GLOBAL-DEFINE OPEN_EXISTING 3
&GLOBAL-DEFINE FILE_SHARE_READ 1                  /* = &H1 */
&GLOBAL-DEFINE FILE_ATTRIBUTE_NORMAL 128       /* = &H80 */

PROCEDURE CreateFileA EXTERNAL "kernel32":
    DEFINE INPUT PARAMETER lpFileName AS CHARACTER.
    DEFINE INPUT PARAMETER dwDesiredAccess AS LONG.
    DEFINE INPUT PARAMETER dwShareMode AS LONG.
    DEFINE INPUT PARAMETER lpSecurityAttributes AS LONG.
    DEFINE INPUT PARAMETER dwCreationDisposition AS LONG.
    DEFINE INPUT PARAMETER dwFlagsAndAttributes AS LONG.
    DEFINE INPUT PARAMETER hTemplateFile AS LONG.
    DEFINE RETURN PARAMETER ReturnValue AS LONG.
END PROCEDURE.

PROCEDURE CloseHandle EXTERNAL "kernel32" :
  DEFINE INPUT  PARAMETER hObject     AS LONG.
  DEFINE RETURN PARAMETER ReturnValue AS LONG.
END PROCEDURE.

DEFINE VARIABLE lpSecurityAtt AS INTEGER NO-UNDO.
DEFINE VARIABLE hObject AS INTEGER NO-UNDO.
DEFINE VARIABLE nReturn AS INTEGER NO-UNDO.

/* Lock file agains writing */
RUN CreateFileA (INPUT source.txt, 
                 INPUT {&GENERIC_WRITE}, 
                 {&FILE_SHARE_READ},
                 lpSecurityAtt, 
                 {&OPEN_EXISTING},
                 {&FILE_ATTRIBUTE_NORMAL},
                 0,
                 OUTPUT hObject).

input from source.txt.
repeat:
  import aline.
  /* do stuff */
end.
input close.

/* Release file handle */
RUN CloseHandle (INPUT hObject, 
                 OUTPUT nReturn).