1 # This file is part of NIT ( http://www.nitlanguage.org ).
3 # Copyright 2004-2008 Jean Privat <jean@pryen.org>
4 # Copyright 2008 Floréal Morandat <morandat@lirmm.fr>
5 # Copyright 2008 Jean-Sébastien Gélinas <calestar@gmail.com>
7 # This file is free software, which comes along with NIT. This software is
8 # distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
9 # without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
10 # PARTICULAR PURPOSE. You can modify it is you want, provided this header
11 # is kept unaltered, and a notification of the changes is added.
12 # You are allowed to redistribute it and sell it, alone or is a part of
15 # File manipulations (create, read, write, etc.)
27 #include <sys/types.h>
35 # `Stream` used to interact with a File or FileDescriptor
36 abstract class FileStream
38 # The path of the file.
39 var path
: nullable String = null
42 private var file
: nullable NativeFile = null
44 # The status of a file. see POSIX stat(2).
45 fun file_stat
: NativeFileStat do return _file
.file_stat
47 # File descriptor of this file
48 fun fd
: Int do return _file
.fileno
52 if _file
== null then return
53 if _file
.address_is_null
then
54 if last_error
!= null then return
55 last_error
= new IOError("Cannot close unopened file")
58 var i
= _file
.io_close
60 last_error
= new IOError("Close failed due to error {sys.errno.strerror}")
65 # Sets the buffering mode for the current FileStream
67 # If the buf_size is <= 0, its value will be 512 by default
69 # The mode is any of the buffer_mode enumeration in `Sys`:
73 fun set_buffering_mode
(buf_size
, mode
: Int) do
74 if buf_size
<= 0 then buf_size
= 512
75 if _file
.set_buffering_type
(buf_size
, mode
) != 0 then
76 last_error
= new IOError("Error while changing buffering type for FileStream, returned error {sys.errno.strerror}")
81 # `Stream` that can read from a File
88 # Open the same file again.
89 # The original path is reused, therefore the reopened file can be a different file.
91 # var f = new FileReader.open("/etc/issue")
94 # assert l == f.read_line
97 if not eof
and not _file
.address_is_null
then close
99 _file
= new NativeFile.io_open_read
(path
.to_cstring
)
100 if _file
.address_is_null
then
101 last_error
= new IOError("Error: Opening file at '{path.as(not null)}' failed with '{sys.errno.strerror}'")
117 redef fun fill_buffer
119 var nb
= _file
.io_read
(_buffer
.items
, _buffer
.capacity
)
129 redef var end_reached
: Bool = false
131 # Open the file at `path` for reading.
133 # var f = new FileReader.open("/etc/issue")
134 # assert not f.end_reached
137 # In case of error, `last_error` is set
139 # f = new FileReader.open("/fail/does not/exist")
140 # assert f.end_reached
141 # assert f.last_error != null
142 init open
(path
: String)
146 _file
= new NativeFile.io_open_read
(path
.to_cstring
)
147 if _file
.address_is_null
then
148 last_error
= new IOError("Error: Opening file at '{path}' failed with '{sys.errno.strerror}'")
153 # Creates a new File stream from a file descriptor
155 # This is a low-level method.
156 init from_fd
(fd
: Int) do
159 _file
= fd
.fd_to_stream
(read_only
)
160 if _file
.address_is_null
then
161 last_error
= new IOError("Error: Converting fd {fd} to stream failed with '{sys.errno.strerror}'")
167 # `Stream` that can write to a File
174 if last_error
!= null then return
175 if not _is_writable
then
176 last_error
= new IOError("Cannot write to non-writable stream")
179 if s
isa FlatText then
180 write_native
(s
.to_cstring
, s
.length
)
182 for i
in s
.substrings
do write_native
(i
.to_cstring
, i
.length
)
191 redef var is_writable
= false
193 # Write `len` bytes from `native`.
194 private fun write_native
(native
: NativeString, len
: Int)
196 if last_error
!= null then return
197 if not _is_writable
then
198 last_error
= new IOError("Cannot write to non-writable stream")
201 if _file
.address_is_null
then
202 last_error
= new IOError("Writing on a null stream")
206 var err
= _file
.io_write
(native
, len
)
209 last_error
= new IOError("Problem in writing : {err} {len} \n")
213 # Open the file at `path` for writing.
214 init open
(path
: String)
216 _file
= new NativeFile.io_open_write
(path
.to_cstring
)
219 if _file
.address_is_null
then
220 last_error
= new IOError("Error: Opening file at '{path}' failed with '{sys.errno.strerror}'")
225 # Creates a new File stream from a file descriptor
226 init from_fd
(fd
: Int) do
228 _file
= fd
.fd_to_stream
(wipe_write
)
230 if _file
.address_is_null
then
231 last_error
= new IOError("Error: Opening stream from file descriptor {fd} failed with '{sys.errno.strerror}'")
238 # Creates a file stream from a file descriptor `fd` using the file access `mode`.
240 # NOTE: The `mode` specified must be compatible with the one used in the file descriptor.
241 private fun fd_to_stream
(mode
: NativeString): NativeFile is extern "file_int_fdtostream"
244 # Constant for read-only file streams
245 private fun read_only
: NativeString do return "r".to_cstring
247 # Constant for write-only file streams
249 # If a stream is opened on a file with this method,
250 # it will wipe the previous file if any.
251 # Else, it will create the file.
252 private fun wipe_write
: NativeString do return "w".to_cstring
254 ###############################################################################
256 # Standard input stream.
258 # The class of the default value of `sys.stdin`.
263 _file
= new NativeFile.native_stdin
268 redef fun poll_in
: Bool is extern "file_stdin_poll_in"
271 # Standard output stream.
273 # The class of the default value of `sys.stdout`.
277 _file
= new NativeFile.native_stdout
280 set_buffering_mode
(256, sys
.buffer_mode_line
)
284 # Standard error stream.
286 # The class of the default value of `sys.stderr`.
290 _file
= new NativeFile.native_stderr
296 ###############################################################################
299 # Like `write_to` but take care of creating the file
300 fun write_to_file
(filepath
: String)
302 var stream
= new FileWriter.open
(filepath
)
308 # Utility class to access file system services
310 # Usually created with `Text::to_path`.
313 private var path
: String
316 redef fun to_s
do return path
318 # Name of the file name at `to_s`
321 # var path = "/tmp/somefile".to_path
322 # assert path.filename == "somefile"
324 var filename
: String = path
.basename
("") is lazy
326 # Does the file at `path` exists?
327 fun exists
: Bool do return stat
!= null
329 # Information on the file at `self` following symbolic links
331 # Returns `null` if there is no file at `self`.
334 # var p = "/tmp/".to_path
336 # if stat != null then # Does `p` exist?
337 # print "It's size is {stat.size}"
338 # if stat.is_dir then print "It's a directory"
341 fun stat
: nullable FileStat
343 var stat
= path
.to_cstring
.file_stat
344 if stat
.address_is_null
then return null
345 return new FileStat(stat
)
348 # Information on the file or link at `self`
350 # Do not follow symbolic links.
351 fun link_stat
: nullable FileStat
353 var stat
= path
.to_cstring
.file_lstat
354 if stat
.address_is_null
then return null
355 return new FileStat(stat
)
358 # Delete a file from the file system, return `true` on success
359 fun delete
: Bool do return path
.to_cstring
.file_delete
361 # Copy content of file at `path` to `dest`
367 var output
= dest
.open_wo
369 while not input
.eof
do
370 var buffer
= input
.read
(1024)
378 # Open this file for reading
380 # Require: `exists and not link_stat.is_dir`
381 fun open_ro
: FileReader
383 # TODO manage streams error when they are merged
384 return new FileReader.open
(path
)
387 # Open this file for writing
389 # Require: `not exists or not stat.is_dir`
390 fun open_wo
: FileWriter
392 # TODO manage streams error when they are merged
393 return new FileWriter.open
(path
)
396 # Read all the content of the file
399 # var content = "/etc/issue".to_path.read_all
403 # See `Reader::read_all` for details.
412 # Read all the lines of the file
415 # var lines = "/etc/passwd".to_path.read_lines
417 # print "{lines.length} users"
420 # var fields = l.split(":")
421 # print "name={fields[0]} uid={fields[2]}"
425 # See `Reader::read_lines` for details.
426 fun read_lines
: Array[String]
429 var res
= s
.read_lines
434 # Return an iterator on each line of the file
437 # for l in "/etc/passwd".to_path.each_line do
438 # var fields = l.split(":")
439 # print "name={fields[0]} uid={fields[2]}"
443 # Note: the stream is automatically closed at the end of the file (see `LineIterator::close_on_finish`)
445 # See `Reader::each_line` for details.
446 fun each_line
: LineIterator
449 var res
= s
.each_line
450 res
.close_on_finish
= true
455 # Lists the name of the files contained within the directory at `path`
457 # Require: `exists and is_dir`
458 fun files
: Array[Path]
460 var files
= new Array[Path]
461 for filename
in path
.files
do
462 files
.add
new Path(path
/ filename
)
467 # Delete a directory and all of its content, return `true` on success
469 # Does not go through symbolic links and may get stuck in a cycle if there
470 # is a cycle in the file system.
474 for file
in self.files
do
475 var stat
= file
.link_stat
477 ok
= file
.rmdir
and ok
479 ok
= file
.delete
and ok
483 # Delete the directory itself
484 if ok
then path
.to_cstring
.rmdir
489 redef fun ==(other
) do return other
isa Path and path
.simplify_path
== other
.path
.simplify_path
490 redef fun hash
do return path
.simplify_path
.hash
493 # Information on a file
495 # Created by `Path::stat` and `Path::link_stat`.
497 # The information within this class is gathered when the instance is initialized
498 # it will not be updated if the targeted file is modified.
504 # The low-level status of a file
507 private var stat
: NativeFileStat
509 private var finalized
= false
513 if not finalized
then
519 # Returns the last access time in seconds since Epoch
520 fun last_access_time
: Int
526 # Returns the last modification time in seconds since Epoch
527 fun last_modification_time
: Int
533 # Size of the file at `path`
540 # Is this a regular file and not a device file, pipe, socket, etc.?
547 # Is this a directory?
554 # Is this a symbolic link?
561 # FIXME Make the following POSIX only? or implement in some other way on Windows
563 # Returns the last status change time in seconds since Epoch
564 fun last_status_change_time
: Int
570 # Returns the permission bits of file
577 # Is this a character device?
584 # Is this a block device?
591 # Is this a FIFO pipe?
598 # Is this a UNIX socket
607 # Access file system related services on the path at `self`
608 fun to_path
: Path do return new Path(to_s
)
612 # return true if a file with this names exists
613 fun file_exists
: Bool do return to_cstring
.file_exists
615 # The status of a file. see POSIX stat(2).
616 fun file_stat
: NativeFileStat do return to_cstring
.file_stat
618 # The status of a file or of a symlink. see POSIX lstat(2).
619 fun file_lstat
: NativeFileStat do return to_cstring
.file_lstat
621 # Remove a file, return true if success
622 fun file_delete
: Bool do return to_cstring
.file_delete
624 # Copy content of file at `self` to `dest`
625 fun file_copy_to
(dest
: String) do to_path
.copy
(dest
.to_path
)
627 # Remove the trailing extension `ext`.
629 # `ext` usually starts with a dot but could be anything.
631 # assert "file.txt".strip_extension(".txt") == "file"
632 # assert "file.txt".strip_extension("le.txt") == "fi"
633 # assert "file.txt".strip_extension("xt") == "file.t"
635 # if `ext` is not present, `self` is returned unmodified.
637 # assert "file.txt".strip_extension(".tar.gz") == "file.txt"
638 fun strip_extension
(ext
: String): String
640 if has_suffix
(ext
) then
641 return substring
(0, length
- ext
.length
)
646 # Extract the basename of a path and remove the extension
648 # assert "/path/to/a_file.ext".basename(".ext") == "a_file"
649 # assert "path/to/a_file.ext".basename(".ext") == "a_file"
650 # assert "path/to".basename(".ext") == "to"
651 # assert "path/to/".basename(".ext") == "to"
652 # assert "path".basename("") == "path"
653 # assert "/path".basename("") == "path"
654 # assert "/".basename("") == "/"
655 # assert "".basename("") == ""
656 fun basename
(ext
: String): String
658 var l
= length
- 1 # Index of the last char
659 while l
> 0 and self.chars
[l
] == '/' do l
-= 1 # remove all trailing `/`
660 if l
== 0 then return "/"
661 var pos
= chars
.last_index_of_from
('/', l
)
664 n
= substring
(pos
+1, l-pos
)
666 return n
.strip_extension
(ext
)
669 # Extract the dirname of a path
671 # assert "/path/to/a_file.ext".dirname == "/path/to"
672 # assert "path/to/a_file.ext".dirname == "path/to"
673 # assert "path/to".dirname == "path"
674 # assert "path/to/".dirname == "path"
675 # assert "path".dirname == "."
676 # assert "/path".dirname == "/"
677 # assert "/".dirname == "/"
678 # assert "".dirname == "."
681 var l
= length
- 1 # Index of the last char
682 while l
> 0 and self.chars
[l
] == '/' do l
-= 1 # remove all trailing `/`
683 var pos
= chars
.last_index_of_from
('/', l
)
685 return substring
(0, pos
)
686 else if pos
== 0 then
693 # Return the canonicalized absolute pathname (see POSIX function `realpath`)
694 fun realpath
: String do
695 var cs
= to_cstring
.file_realpath
696 var res
= cs
.to_s_with_copy
697 # cs.free_malloc # FIXME memory leak
701 # Simplify a file path by remove useless ".", removing "//", and resolving ".."
703 # * ".." are not resolved if they start the path
704 # * starting "/" is not removed
705 # * trailing "/" is removed
707 # Note that the method only work on the string:
709 # * no I/O access is performed
710 # * the validity of the path is not checked
713 # assert "some/./complex/../../path/from/../to/a////file//".simplify_path == "path/to/a/file"
714 # assert "../dir/file".simplify_path == "../dir/file"
715 # assert "dir/../../".simplify_path == ".."
716 # assert "dir/..".simplify_path == "."
717 # assert "//absolute//path/".simplify_path == "/absolute/path"
718 # assert "//absolute//../".simplify_path == "/"
720 fun simplify_path
: String
722 var a
= self.split_with
("/")
723 var a2
= new Array[String]
725 if x
== "." then continue
726 if x
== "" and not a2
.is_empty
then continue
727 if x
== ".." and not a2
.is_empty
and a2
.last
!= ".." then
733 if a2
.is_empty
then return "."
734 if a2
.length
== 1 and a2
.first
== "" then return "/"
738 # Correctly join two path using the directory separator.
740 # Using a standard "{self}/{path}" does not work in the following cases:
743 # * `path` starts with `'/'`.
745 # This method ensures that the join is valid.
747 # assert "hello".join_path("world") == "hello/world"
748 # assert "hel/lo".join_path("wor/ld") == "hel/lo/wor/ld"
749 # assert "".join_path("world") == "world"
750 # assert "hello".join_path("/world") == "/world"
751 # assert "hello/".join_path("world") == "hello/world"
752 # assert "hello/".join_path("/world") == "/world"
754 # Note: You may want to use `simplify_path` on the result.
756 # Note: This method works only with POSIX paths.
757 fun join_path
(path
: String): String
759 if path
.is_empty
then return self
760 if self.is_empty
then return path
761 if path
.chars
[0] == '/' then return path
762 if self.last
== '/' then return "{self}{path}"
763 return "{self}/{path}"
766 # Convert the path (`self`) to a program name.
768 # Ensure the path (`self`) will be treated as-is by POSIX shells when it is
769 # used as a program name. In order to do that, prepend `./` if needed.
771 # assert "foo".to_program_name == "./foo"
772 # assert "/foo".to_program_name == "/foo"
773 # assert "".to_program_name == "./" # At least, your shell will detect the error.
774 fun to_program_name
: String do
775 if self.has_prefix
("/") then
782 # Alias for `join_path`
784 # assert "hello" / "world" == "hello/world"
785 # assert "hel/lo" / "wor/ld" == "hel/lo/wor/ld"
786 # assert "" / "world" == "world"
787 # assert "/hello" / "/world" == "/world"
789 # This operator is quite useful for chaining changes of path.
790 # The next one being relative to the previous one.
794 # var c = "baz/foobar"
795 # assert a/b/c == "/bar/baz/foobar"
796 fun /(path
: String): String do return join_path
(path
)
798 # Returns the relative path needed to go from `self` to `dest`.
800 # assert "/foo/bar".relpath("/foo/baz") == "../baz"
801 # assert "/foo/bar".relpath("/baz/bar") == "../../baz/bar"
803 # If `self` or `dest` is relative, they are considered relatively to `getcwd`.
805 # In some cases, the result is still independent of the current directory:
807 # assert "foo/bar".relpath("..") == "../../.."
809 # In other cases, parts of the current directory may be exhibited:
811 # var p = "../foo/bar".relpath("baz")
812 # var c = getcwd.basename("")
813 # assert p == "../../{c}/baz"
815 # For path resolution independent of the current directory (eg. for paths in URL),
816 # or to use an other starting directory than the current directory,
817 # just force absolute paths:
819 # var start = "/a/b/c/d"
820 # var p2 = (start/"../foo/bar").relpath(start/"baz")
821 # assert p2 == "../../d/baz"
824 # Neither `self` or `dest` has to be real paths or to exist in directories since
825 # the resolution is only done with string manipulations and without any access to
826 # the underlying file system.
828 # If `self` and `dest` are the same directory, the empty string is returned:
830 # assert "foo".relpath("foo") == ""
831 # assert "foo/../bar".relpath("bar") == ""
833 # The empty string and "." designate both the current directory:
835 # assert "".relpath("foo/bar") == "foo/bar"
836 # assert ".".relpath("foo/bar") == "foo/bar"
837 # assert "foo/bar".relpath("") == "../.."
838 # assert "/" + "/".relpath(".") == getcwd
839 fun relpath
(dest
: String): String
842 var from
= (cwd
/self).simplify_path
.split
("/")
843 if from
.last
.is_empty
then from
.pop
# case for the root directory
844 var to
= (cwd
/dest
).simplify_path
.split
("/")
845 if to
.last
.is_empty
then to
.pop
# case for the root directory
847 # Remove common prefixes
848 while not from
.is_empty
and not to
.is_empty
and from
.first
== to
.first
do
853 # Result is going up in `from` with ".." then going down following `to`
854 var from_len
= from
.length
855 if from_len
== 0 then return to
.join
("/")
856 var up
= "../"*(from_len-1
) + ".."
857 if to
.is_empty
then return up
858 var res
= up
+ "/" + to
.join
("/")
862 # Create a directory (and all intermediate directories if needed)
865 var dirs
= self.split_with
("/")
866 var path
= new FlatBuffer
867 if dirs
.is_empty
then return
868 if dirs
[0].is_empty
then
869 # it was a starting /
873 if d
.is_empty
then continue
876 path
.to_s
.to_cstring
.file_mkdir
880 # Delete a directory and all of its content, return `true` on success
882 # Does not go through symbolic links and may get stuck in a cycle if there
883 # is a cycle in the filesystem.
884 fun rmdir
: Bool do return to_path
.rmdir
886 # Change the current working directory
889 # assert getcwd == "/etc"
891 # assert getcwd == "/"
894 fun chdir
do to_cstring
.file_chdir
896 # Return right-most extension (without the dot)
898 # Only the last extension is returned.
899 # There is no special case for combined extensions.
901 # assert "file.txt".file_extension == "txt"
902 # assert "file.tar.gz".file_extension == "gz"
904 # For file without extension, `null` is returned.
905 # Hoever, for trailing dot, `""` is returned.
907 # assert "file".file_extension == null
908 # assert "file.".file_extension == ""
910 # The starting dot of hidden files is never considered.
912 # assert ".file.txt".file_extension == "txt"
913 # assert ".file".file_extension == null
914 fun file_extension
: nullable String
916 var last_slash
= chars
.last_index_of
('.')
917 if last_slash
> 0 then
918 return substring
( last_slash
+1, length
)
924 # returns files contained within the directory represented by self
925 fun files
: Array[String] is extern import Array[String], Array[String].add
, NativeString.to_s
, String.to_cstring
`{
929 dir_path = String_to_cstring( recv );
930 if ((dir = opendir(dir_path)) == NULL)
937 Array_of_String results;
941 results = new_Array_of_String();
943 while ( ( de = readdir( dir ) ) != NULL )
944 if ( strcmp( de->d_name, ".." ) != 0 &&
945 strcmp( de->d_name, "." ) != 0 )
947 file_name = NativeString_to_s( strdup( de->d_name ) );
948 Array_of_String_add( results, file_name );
957 redef class NativeString
958 private fun file_exists
: Bool is extern "string_NativeString_NativeString_file_exists_0"
959 private fun file_stat
: NativeFileStat is extern "string_NativeString_NativeString_file_stat_0"
960 private fun file_lstat
: NativeFileStat `{
961 struct stat* stat_element;
963 stat_element = malloc(sizeof(struct stat));
964 res = lstat(recv, stat_element);
965 if (res == -1) return NULL;
968 private fun file_mkdir
: Bool is extern "string_NativeString_NativeString_file_mkdir_0"
969 private fun rmdir
: Bool `{ return rmdir(recv); `}
970 private fun file_delete: Bool is extern "string_NativeString_NativeString_file_delete_0"
971 private fun file_chdir is extern "string_NativeString_NativeString_file_chdir_0"
972 private fun file_realpath: NativeString is extern "file_NativeString_realpath"
975 # This class is system dependent ... must reify the vfs
976 extern class NativeFileStat `{ struct stat * `}
977 # Returns the permission bits of file
978 fun mode
: Int is extern "file_FileStat_FileStat_mode_0"
979 # Returns the last access time
980 fun atime
: Int is extern "file_FileStat_FileStat_atime_0"
981 # Returns the last status change time
982 fun ctime
: Int is extern "file_FileStat_FileStat_ctime_0"
983 # Returns the last modification time
984 fun mtime
: Int is extern "file_FileStat_FileStat_mtime_0"
986 fun size
: Int is extern "file_FileStat_FileStat_size_0"
988 # Returns true if it is a regular file (not a device file, pipe, sockect, ...)
989 fun is_reg
: Bool `{ return S_ISREG(recv->st_mode); `}
990 # Returns true if it is a directory
991 fun is_dir: Bool `{ return S_ISDIR(recv->st_mode); `}
992 # Returns true if it is a character device
993 fun is_chr
: Bool `{ return S_ISCHR(recv->st_mode); `}
994 # Returns true if it is a block device
995 fun is_blk: Bool `{ return S_ISBLK(recv->st_mode); `}
996 # Returns true if the type is fifo
997 fun is_fifo
: Bool `{ return S_ISFIFO(recv->st_mode); `}
998 # Returns true if the type is a link
999 fun is_lnk: Bool `{ return S_ISLNK(recv->st_mode); `}
1000 # Returns true if the type is a socket
1001 fun is_sock
: Bool `{ return S_ISSOCK(recv->st_mode); `}
1004 # Instance of this class are standard FILE * pointers
1005 private extern class NativeFile `{ FILE* `}
1006 fun io_read
(buf
: NativeString, len
: Int): Int is extern "file_NativeFile_NativeFile_io_read_2"
1007 fun io_write
(buf
: NativeString, len
: Int): Int is extern "file_NativeFile_NativeFile_io_write_2"
1008 fun io_close
: Int is extern "file_NativeFile_NativeFile_io_close_0"
1009 fun file_stat
: NativeFileStat is extern "file_NativeFile_NativeFile_file_stat_0"
1010 fun fileno
: Int `{ return fileno(recv); `}
1011 # Flushes the buffer, forcing the write operation
1012 fun flush: Int is extern "fflush"
1013 # Used to specify how the buffering will be handled for the current stream.
1014 fun set_buffering_type(buf_length: Int, mode: Int): Int is extern "file_NativeFile_NativeFile_set_buffering_type_0"
1016 new io_open_read(path: NativeString) is extern "file_NativeFileCapable_NativeFileCapable_io_open_read_1"
1017 new io_open_write(path: NativeString) is extern "file_NativeFileCapable_NativeFileCapable_io_open_write_1"
1018 new native_stdin is extern "file_NativeFileCapable_NativeFileCapable_native_stdin_0"
1019 new native_stdout is extern "file_NativeFileCapable_NativeFileCapable_native_stdout_0"
1020 new native_stderr is extern "file_NativeFileCapable_NativeFileCapable_native_stderr_0"
1026 var stdin: PollableReader = new Stdin is protected writable, lazy
1029 var stdout: Writer = new Stdout is protected writable, lazy
1031 # Standard output for errors
1032 var stderr: Writer = new Stderr is protected writable, lazy
1034 # Enumeration for buffer mode full (flushes when buffer is full)
1035 fun buffer_mode_full: Int is extern "file_Sys_Sys_buffer_mode_full_0"
1036 # Enumeration for buffer mode line (flushes when a `\n
` is encountered)
1037 fun buffer_mode_line: Int is extern "file_Sys_Sys_buffer_mode_line_0"
1038 # Enumeration for buffer mode none (flushes ASAP when something is written)
1039 fun buffer_mode_none: Int is extern "file_Sys_Sys_buffer_mode_none_0"
1041 # returns first available stream to read or write to
1042 # return null on interruption (possibly a signal)
1043 protected fun poll( streams : Sequence[FileStream] ) : nullable FileStream
1045 var in_fds = new Array[Int]
1046 var out_fds = new Array[Int]
1047 var fd_to_stream = new HashMap[Int,FileStream]
1050 if s isa FileReader then in_fds.add( fd )
1051 if s isa FileWriter then out_fds.add( fd )
1053 fd_to_stream[fd] = s
1056 var polled_fd = intern_poll( in_fds, out_fds )
1058 if polled_fd == null then
1061 return fd_to_stream[polled_fd]
1065 private fun intern_poll(in_fds: Array[Int], out_fds: Array[Int]) : nullable Int is extern import Array[Int].length, Array[Int].[], Int.as(nullable Int) `{
1066 int in_len
, out_len
, total_len
;
1067 struct pollfd
*c_fds
;
1070 int first_polled_fd
= -1;
1073 in_len
= Array_of_Int_length( in_fds
);
1074 out_len
= Array_of_Int_length( out_fds
);
1075 total_len
= in_len
+ out_len
;
1076 c_fds
= malloc
( sizeof
(struct pollfd
) * total_len
);
1079 for ( i
=0; i
<in_len
; i
++ ) {
1081 fd
= Array_of_Int__index( in_fds
, i
);
1084 c_fds
[i
].events
= POLLIN;
1087 /* output streams
*/
1088 for ( i
=0; i
<out_len
; i
++ ) {
1090 fd
= Array_of_Int__index( out_fds
, i
);
1093 c_fds
[i
].events
= POLLOUT;
1096 /* poll all fds
, unlimited timeout
*/
1097 result
= poll
( c_fds
, total_len
, -1 );
1100 /* analyse results
*/
1101 for ( i
=0; i
<total_len
; i
++ )
1102 if ( c_fds
[i
].revents
& c_fds
[i
].events
|| /* awaited event
*/
1103 c_fds
[i
].revents
& POLLHUP ) /* closed
*/
1105 first_polled_fd
= c_fds
[i
].fd
;
1109 return Int_as_nullable( first_polled_fd
);
1111 else if ( result
< 0 )
1112 fprintf
( stderr
, "Error in Stream:poll: %s\n", strerror
( errno
) );
1119 # Print `objects
` on the standard output (`stdout
`).
1120 protected fun printn(objects: Object...)
1122 sys.stdout.write(objects.to_s)
1125 # Print an `object
` on the standard output (`stdout
`) and add a newline.
1126 protected fun print(object: Object)
1128 sys.stdout.write(object.to_s)
1129 sys.stdout.write("\n")
1132 # Read a character from the standard input (`stdin
`).
1133 protected fun getc: Char
1135 return sys.stdin.read_char.ascii
1138 # Read a line from the standard input (`stdin
`).
1139 protected fun gets: String
1141 return sys.stdin.read_line
1144 # Return the working (current) directory
1145 protected fun getcwd: String do return file_getcwd.to_s
1146 private fun file_getcwd: NativeString is extern "string_NativeString_NativeString_file_getcwd_0"