:: krowemoh

Thursday | 26 DEC 2024
Posts Links Other About Now

previous
next

Checking if a File is a Directory in BASIC

2023-12-25
universe, pick, basic

A handy little snippet to check if a file is a directory from BASIC.

I'm not sure if this is the best way so this could change. The problem is that BASIC doesn't have a STAT function to get the file information of a path. This means that we need to try to do an OPENPATH and see what happens.

*
   FILE.PATH = '/path/to/folder'
* 
   OPENPATH FILE.PATH TO TEST.FILE THEN
      IS.DIR = 1
   END ELSE
      IS.DIR = 0
   END
*

If the OPENPATH succeeds then we have a directory, otherwise we have a regular file.

With this logic we can then recursively open directories and get all the files within.

The below implementation is using internal subroutines with a stack to recursively get the files. I'm still working on how to write a general purpose subroutine that I could call. This might need to be a set of programs.

   EQU TRUE TO 1
   EQU FALSE TO 0
*
   EQU STACK.SIZE TO 100
   DIM STACK(STACK.SIZE)
   MAT STACK = ''
*
*
   FILE.PATH = '/home/media/animated/Infinity Train'
*
   GOSUB IS.DIR
*
   IF NOT(IS.DIR) THEN
      PRINT 'File: ' : FILE.PATH
      RETURN
   END
*
   GOSUB GET.FILES
*
   STOP
*
*********************  S U B R O U T I N E  *********************
*
GET.FILES:NULL
*
   NUMBER.OF.FILES = DCOUNT(DIR.LIST,@AM)
*
   PATH = FILE.PATH
*
   FOR F.CTR = 1 TO NUMBER.OF.FILES
      FILE.NAME = DIR.LIST<F.CTR>
      FILE.PATH = PATH : '/' : FILE.NAME
*
      S = ''
      S<1> = LOWER(DIR.LIST)
      S<2> = F.CTR
      S<3> = PATH
      S<4> = NUMBER.OF.FILES
*
      GOSUB IS.DIR
*
      IF NOT(IS.DIR) THEN
         PRINT 'File: ' : FILE.PATH
         S = ''
         CONTINUE
      END
*
      PRINT 'DIR: ' : FILE.PATH
*
      CALL STACK.PUSH(MAT STACK,STACK.SIZE,S)
      GOSUB GET.FILES
      CALL STACK.POP(MAT STACK,STACK.SIZE,S)
*
      DIR.LIST = RAISE(S<1>)
      F.CTR = S<2>
      PATH =  S<3>
      NUMBER.OF.FILES = S<4>
   NEXT F.CTR
*
   RETURN
*
*********************  S U B R O U T I N E  *********************
*
IS.DIR:NULL
*
   OPENPATH FILE.PATH TO TEST.FILE THEN
      IS.DIR = TRUE
*
      CLEARSELECT
*
      SELECT TEST.FILE
*
      READLIST DIR.LIST ELSE
         PRINT 'Trying to select an invalid directory.'
         STOP
      END
*
      CLEARSELECT
*
   END ELSE
      IS.DIR = FALSE
   END
*
   RETURN
*
* END OF PROGRAM
*
   END