File tests

In addition to writing to and reading from files, you can perform a variety of tests on files.

The following process rule will fire only when the file foo.txt exists:

  process when file "foo.txt" exists
     reopen foo
     put foo "Mary had a little lamb.%n"
     close foo

If you want to do one thing when the file exists and another if it does not, you can use the test in a do...done block:

  process
     do when file "foo.txt" exists
        reopen foo
        put foo "Its fleece was white as snow.%n"
        close foo
  
     else
        open foo as file "foo.txt"
        put foo "Mary had a little lamb,%n"
        close foo
     done

You can also test for the readability and writability of a file as follows:

  process when file "foo.txt" isnt readable
     output "File foo.txt cannot be read.%n"
         || "Check your file and directory permissions.%n"
  
  process when file "foo.txt" isnt writable
     output "File foo.txt cannot be written.%n"
         || "Check your file and directory permissions.%n"

The results of these tests can be reversed by using is rather than isnt.

Finally, you can test whether a named file is a file or a directory:

  process when file "foo.txt" is file
     submit file "foo.txt"
  
  process when file "foo.txt" is directory
     output "Error: foo.txt is a directory.%n"

These tests can also be reversed by replacing is with isnt.

File tests are not often needed in OmniMark programs because the default handling of file input and output errors is often appropriate. If an error is encountered when attempting to read from or write to a file, OmniMark will generate an error message that specifies the error encountered and the name of the file involved. The program then terminates.

Error messages will be generated when any of the following problems are encountered:

  • the name given for a file is actually the name of a directory,
  • a file that the program is attempting to read from does not exist,
  • a file that the program is attempting to read from exists, but the directory and file permissions are such that it cannot be opened for reading,
  • the program cannot write to a file because the file permissions are such that the file cannot be created, and
  • the directory to which the program is attempting to write has permissions set that do not allow the program to create the file.

File tests exist so that you can specify different handling procedures for file input and output errors.