Search code examples
progress-4glopenedgedatestamp

How do I get the latest file from a directory in Progress 4gl?


DEFINE VARIABLE cDir  AS CHARACTER NO-UNDO initial '/home/raj/'.

define temp-table tt-file
       field tfile as char format "x(22)".
define variable vfile as char format "x(22)" no-undo.

INPUT FROM OS-DIR (cDir) ECHO.

REPEAT:

    create tt-file.
    IMPORT tt-file.tfile.
        FILE-INFO:FILE-NAME = cDir + tt-file.tfile.
      if file-info:file-name begins cdir + "RATES"
         and string(month(file-info:file-mod-date)) = string(month(today)) THEN    
     DISPLAY tt-file.tfile FORMAT "X(22)" LABEL 'name of the file'
             FILE-INFO:FULL-PATHNAME FORMAT "X(21)" LABEL 'FULL-PATHNAME'
             FILE-INFO:PATHNAME FORMAT "X(30)" LABEL 'PATHNAME'
             FILE-INFO:FILE-TYPE FORMAT "X(5)" LABEL 'FILE-TYPE'
             file-info:file-mod-date.
end.

The problem I face is I have multiple files for the current month but I need to get latest file for the month.


Solution

  • Why not add two fields for file creation: date & time? Then you can easily write a simple WHERE-clause that get's you the last file between two dates.

    DEFINE VARIABLE cDir  AS CHARACTER NO-UNDO INITIAL '/home/raj/'.
    
    DEFINE TEMP-TABLE tt-file NO-UNDO
           FIELD tfile      AS CHARACTER FORMAT "x(22)"
           FIELD createDate AS DATE
           FIELD createTime AS INTEGER.
    
    INPUT FROM OS-DIR (cDir).
    REPEAT:
        CREATE tt-file.
        IMPORT tt-file.tfile.
    
        FILE-INFO:FILE-NAME = cDir + tt-file.tfile.
    
        ASSIGN 
            tt-file.createDate = FILE-INFO:FILE-CREATE-DATE
            tt-file.createtime = FILE-INFO:FILE-CREATE-TIME.
    END.
    
    /* Here you could add any logic to get your file */
    FOR EACH tt-file NO-LOCK BY tt-file.createDate BY tt-file.createtime:
        DISP tt-file.
    END.
    
    /* Updated example for doing things only with .csv files */
    FOR EACH tt-file NO-LOCK WHERE tt-file.tfile MATCHES "*csv" 
                                BY tt-file.createDate 
                                BY tt-file.createtime:
        DISP tt-file.
    END.
    

    Depending on your application you might want to use FILE-MOD-DATE & FILE-MOD-TIME instead.