open

open — attempts to open a file.

Syntax

open (filename, mode, use_parser?)

		

Arguments

filename

A filename (possibly including the path), as a string.

mode

A string indicating the mode for the file: "r" for read-only, "w" for writable, "a" for append.

use_parser

Assume Lisp grammar regardless of the default grammar.

Returns

A file pointer, or nil if the request failed.

Description

This function attempts to open a file. If the file is opened for write ("w"), any previously existing file of the same name will be destroyed. If the file is opened for append ("a") then a previously existing file will be lengthened with subsequent writes, but the data in that file will not be damaged. A file can only be opened read-only ("r") if it already exists. The result of this function may be used as an argument to a variety of read and write operations.

[Note]

When Gamma opens or creates a file, it creates an abstract file pointer. A printed representation of the file pointer looks like this: #<File:filename>. This representation cannot be read back in to Gamma, and so a symbol must be assigned to the file pointer in order to refer to or work with a file. In common language, we refer to this symbol as the file pointer. For instance, in the examples below, we would say the symbol fp is the file pointer. (See also Referencing Files.)

If use_parser is non-nil, then a call to read will parse the file according to its default grammar. If use_parser is nil, then a call to read will parse the file as if it were a Lisp expression. A file must be opened in Lisp format in order to use calls to read_char, read_double, read_float, read_line, read_long, read_short and read_until.

Examples

An input file contains the following:

      (setq y 5)

Calling open will produce:

Gamma> fp = open ("myopenfile.dat", "r", nil);
#<File:"myopenfile.dat">
Gamma> princ(read_line(fp), "\n");
(setq y 5)
t
Gamma> fp = open ("myopenfile.dat", "r", nil);
#<File:"myopenfile.dat">
Gamma> eval (read(fp));
5
Gamma> fp = open ("myopenfile.dat", "r", t);
#<File:"myopenfile.dat">
Gamma> princ(read_line(fp), "\n");
(setq y 5)
t
Gamma> fp = open ("myopenfile.dat", "r", t);
#<File:"myopenfile.dat">
Gamma> eval (read(fp));
Error: ./generate.slg: line 1: Malformed expression within ()
Error: ./generate.slg: line 1: Unexpected end of file
Macro read left extra stuff on the LISP stack: 8098478, 8098470
nil
nil
Gamma>  

The following example opens and reads a file, if it exists. If not, it prints and error message.

if ( (fp=open("myfile","r")) != nil )
{
  local line;
  while((line = read_line(fp)) != _eof_)
    {
      princ(line, "\n");
    }
  close(fp);
}
else
{
	princ("Error : unable to open myfile for read\n");
}
		

See Also

close, fd_open, open_string, read, read_char, read_double, read_float, read_line, read_long, read_short, read_until, seek, tell, terpri, write, writec