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).
46 # var f = new FileReader.open("/etc/issue")
47 # assert f.file_stat.is_file
49 # Return null in case of error
50 fun file_stat
: nullable FileStat
52 var stat
= _file
.file_stat
53 if stat
.address_is_null
then return null
54 return new FileStat(stat
)
57 # File descriptor of this file
58 fun fd
: Int do return _file
.fileno
62 if _file
== null then return
63 if _file
.address_is_null
then
64 if last_error
!= null then return
65 last_error
= new IOError("Cannot close unopened file")
68 var i
= _file
.io_close
70 last_error
= new IOError("Close failed due to error {sys.errno.strerror}")
75 # Sets the buffering mode for the current FileStream
77 # If the buf_size is <= 0, its value will be 512 by default
79 # The mode is any of the buffer_mode enumeration in `Sys`:
83 fun set_buffering_mode
(buf_size
, mode
: Int) do
84 if buf_size
<= 0 then buf_size
= 512
85 if _file
.set_buffering_type
(buf_size
, mode
) != 0 then
86 last_error
= new IOError("Error while changing buffering type for FileStream, returned error {sys.errno.strerror}")
91 # `Stream` that can read from a File
98 # Open the same file again.
99 # The original path is reused, therefore the reopened file can be a different file.
101 # var f = new FileReader.open("/etc/issue")
102 # var l = f.read_line
104 # assert l == f.read_line
107 if not eof
and not _file
.address_is_null
then close
109 _file
= new NativeFile.io_open_read
(path
.to_cstring
)
110 if _file
.address_is_null
then
111 last_error
= new IOError("Error: Opening file at '{path.as(not null)}' failed with '{sys.errno.strerror}'")
127 redef fun fill_buffer
129 var nb
= _file
.io_read
(_buffer
.items
, _buffer
.capacity
)
139 redef var end_reached
: Bool = false
141 # Open the file at `path` for reading.
143 # var f = new FileReader.open("/etc/issue")
144 # assert not f.end_reached
147 # In case of error, `last_error` is set
149 # f = new FileReader.open("/fail/does not/exist")
150 # assert f.end_reached
151 # assert f.last_error != null
152 init open
(path
: String)
156 _file
= new NativeFile.io_open_read
(path
.to_cstring
)
157 if _file
.address_is_null
then
158 last_error
= new IOError("Error: Opening file at '{path}' failed with '{sys.errno.strerror}'")
163 # Creates a new File stream from a file descriptor
165 # This is a low-level method.
166 init from_fd
(fd
: Int) do
169 _file
= fd
.fd_to_stream
(read_only
)
170 if _file
.address_is_null
then
171 last_error
= new IOError("Error: Converting fd {fd} to stream failed with '{sys.errno.strerror}'")
177 # `Stream` that can write to a File
184 if last_error
!= null then return
185 if not _is_writable
then
186 last_error
= new IOError("Cannot write to non-writable stream")
189 if s
isa FlatText then
190 write_native
(s
.to_cstring
, s
.length
)
192 for i
in s
.substrings
do write_native
(i
.to_cstring
, i
.length
)
201 redef var is_writable
= false
203 # Write `len` bytes from `native`.
204 private fun write_native
(native
: NativeString, len
: Int)
206 if last_error
!= null then return
207 if not _is_writable
then
208 last_error
= new IOError("Cannot write to non-writable stream")
211 if _file
.address_is_null
then
212 last_error
= new IOError("Writing on a null stream")
216 var err
= _file
.io_write
(native
, len
)
219 last_error
= new IOError("Problem in writing : {err} {len} \n")
223 # Open the file at `path` for writing.
224 init open
(path
: String)
226 _file
= new NativeFile.io_open_write
(path
.to_cstring
)
229 if _file
.address_is_null
then
230 last_error
= new IOError("Error: Opening file at '{path}' failed with '{sys.errno.strerror}'")
235 # Creates a new File stream from a file descriptor
236 init from_fd
(fd
: Int) do
238 _file
= fd
.fd_to_stream
(wipe_write
)
240 if _file
.address_is_null
then
241 last_error
= new IOError("Error: Opening stream from file descriptor {fd} failed with '{sys.errno.strerror}'")
248 # Creates a file stream from a file descriptor `fd` using the file access `mode`.
250 # NOTE: The `mode` specified must be compatible with the one used in the file descriptor.
251 private fun fd_to_stream
(mode
: NativeString): NativeFile is extern "file_int_fdtostream"
254 # Constant for read-only file streams
255 private fun read_only
: NativeString do return once
"r".to_cstring
257 # Constant for write-only file streams
259 # If a stream is opened on a file with this method,
260 # it will wipe the previous file if any.
261 # Else, it will create the file.
262 private fun wipe_write
: NativeString do return once
"w".to_cstring
264 ###############################################################################
266 # Standard input stream.
268 # The class of the default value of `sys.stdin`.
273 _file
= new NativeFile.native_stdin
278 redef fun poll_in
: Bool is extern "file_stdin_poll_in"
281 # Standard output stream.
283 # The class of the default value of `sys.stdout`.
287 _file
= new NativeFile.native_stdout
290 set_buffering_mode
(256, sys
.buffer_mode_line
)
294 # Standard error stream.
296 # The class of the default value of `sys.stderr`.
300 _file
= new NativeFile.native_stderr
306 ###############################################################################
309 # Like `write_to` but take care of creating the file
310 fun write_to_file
(filepath
: String)
312 var stream
= new FileWriter.open
(filepath
)
318 # Utility class to access file system services
320 # Usually created with `Text::to_path`.
323 private var path
: String
326 redef fun to_s
do return path
328 # Name of the file name at `to_s`
331 # var path = "/tmp/somefile".to_path
332 # assert path.filename == "somefile"
334 var filename
: String = path
.basename
("") is lazy
336 # Does the file at `path` exists?
337 fun exists
: Bool do return stat
!= null
339 # Information on the file at `self` following symbolic links
341 # Returns `null` if there is no file at `self`.
343 # assert "/etc/".to_path.stat.is_dir
344 # assert "/etc/issue".to_path.stat.is_file
345 # assert "/fail/does not/exist".to_path.stat == null
348 # var p = "/tmp/".to_path
350 # if stat != null then # Does `p` exist?
351 # print "It's size is {stat.size}"
352 # if stat.is_dir then print "It's a directory"
355 fun stat
: nullable FileStat
357 var stat
= path
.to_cstring
.file_stat
358 if stat
.address_is_null
then return null
359 return new FileStat(stat
)
362 # Information on the file or link at `self`
364 # Do not follow symbolic links.
365 fun link_stat
: nullable FileStat
367 var stat
= path
.to_cstring
.file_lstat
368 if stat
.address_is_null
then return null
369 return new FileStat(stat
)
372 # Delete a file from the file system, return `true` on success
373 fun delete
: Bool do return path
.to_cstring
.file_delete
375 # Copy content of file at `path` to `dest`
381 var output
= dest
.open_wo
383 while not input
.eof
do
384 var buffer
= input
.read
(1024)
392 # Open this file for reading
394 # Require: `exists and not link_stat.is_dir`
395 fun open_ro
: FileReader
397 # TODO manage streams error when they are merged
398 return new FileReader.open
(path
)
401 # Open this file for writing
403 # Require: `not exists or not stat.is_dir`
404 fun open_wo
: FileWriter
406 # TODO manage streams error when they are merged
407 return new FileWriter.open
(path
)
410 # Read all the content of the file
413 # var content = "/etc/issue".to_path.read_all
417 # See `Reader::read_all` for details.
426 # Read all the lines of the file
429 # var lines = "/etc/passwd".to_path.read_lines
431 # print "{lines.length} users"
434 # var fields = l.split(":")
435 # print "name={fields[0]} uid={fields[2]}"
439 # See `Reader::read_lines` for details.
440 fun read_lines
: Array[String]
443 var res
= s
.read_lines
448 # Return an iterator on each line of the file
451 # for l in "/etc/passwd".to_path.each_line do
452 # var fields = l.split(":")
453 # print "name={fields[0]} uid={fields[2]}"
457 # Note: the stream is automatically closed at the end of the file (see `LineIterator::close_on_finish`)
459 # See `Reader::each_line` for details.
460 fun each_line
: LineIterator
463 var res
= s
.each_line
464 res
.close_on_finish
= true
469 # Lists the name of the files contained within the directory at `path`
471 # Require: `exists and is_dir`
472 fun files
: Array[Path]
474 var files
= new Array[Path]
475 for filename
in path
.files
do
476 files
.add
new Path(path
/ filename
)
481 # Delete a directory and all of its content, return `true` on success
483 # Does not go through symbolic links and may get stuck in a cycle if there
484 # is a cycle in the file system.
488 for file
in self.files
do
489 var stat
= file
.link_stat
491 ok
= file
.rmdir
and ok
493 ok
= file
.delete
and ok
497 # Delete the directory itself
498 if ok
then ok
= path
.to_cstring
.rmdir
and ok
503 redef fun ==(other
) do return other
isa Path and path
.simplify_path
== other
.path
.simplify_path
504 redef fun hash
do return path
.simplify_path
.hash
507 # Information on a file
509 # Created by `Path::stat` and `Path::link_stat`.
511 # The information within this class is gathered when the instance is initialized
512 # it will not be updated if the targeted file is modified.
518 # The low-level status of a file
521 private var stat
: NativeFileStat
523 private var finalized
= false
527 if not finalized
then
533 # Returns the last access time in seconds since Epoch
534 fun last_access_time
: Int
540 # Returns the last access time
542 # alias for `last_access_time`
543 fun atime
: Int do return last_access_time
545 # Returns the last modification time in seconds since Epoch
546 fun last_modification_time
: Int
552 # Returns the last modification time
554 # alias for `last_modification_time`
555 fun mtime
: Int do return last_modification_time
558 # Size of the file at `path`
565 # Is self a regular file and not a device file, pipe, socket, etc.?
572 # Alias for `is_file`
573 fun is_reg
: Bool do return is_file
575 # Is this a directory?
582 # Is this a symbolic link?
589 # FIXME Make the following POSIX only? or implement in some other way on Windows
591 # Returns the last status change time in seconds since Epoch
592 fun last_status_change_time
: Int
598 # Returns the last status change time
600 # alias for `last_status_change_time`
601 fun ctime
: Int do return last_status_change_time
603 # Returns the permission bits of file
610 # Is this a character device?
617 # Is this a block device?
624 # Is this a FIFO pipe?
631 # Is this a UNIX socket
640 # Access file system related services on the path at `self`
641 fun to_path
: Path do return new Path(to_s
)
645 # return true if a file with this names exists
646 fun file_exists
: Bool do return to_cstring
.file_exists
648 # The status of a file. see POSIX stat(2).
649 fun file_stat
: nullable FileStat
651 var stat
= to_cstring
.file_stat
652 if stat
.address_is_null
then return null
653 return new FileStat(stat
)
656 # The status of a file or of a symlink. see POSIX lstat(2).
657 fun file_lstat
: nullable FileStat
659 var stat
= to_cstring
.file_lstat
660 if stat
.address_is_null
then return null
661 return new FileStat(stat
)
664 # Remove a file, return true if success
665 fun file_delete
: Bool do return to_cstring
.file_delete
667 # Copy content of file at `self` to `dest`
668 fun file_copy_to
(dest
: String) do to_path
.copy
(dest
.to_path
)
670 # Remove the trailing extension `ext`.
672 # `ext` usually starts with a dot but could be anything.
674 # assert "file.txt".strip_extension(".txt") == "file"
675 # assert "file.txt".strip_extension("le.txt") == "fi"
676 # assert "file.txt".strip_extension("xt") == "file.t"
678 # if `ext` is not present, `self` is returned unmodified.
680 # assert "file.txt".strip_extension(".tar.gz") == "file.txt"
681 fun strip_extension
(ext
: String): String
683 if has_suffix
(ext
) then
684 return substring
(0, length
- ext
.length
)
689 # Extract the basename of a path and remove the extension
691 # assert "/path/to/a_file.ext".basename(".ext") == "a_file"
692 # assert "path/to/a_file.ext".basename(".ext") == "a_file"
693 # assert "path/to".basename(".ext") == "to"
694 # assert "path/to/".basename(".ext") == "to"
695 # assert "path".basename("") == "path"
696 # assert "/path".basename("") == "path"
697 # assert "/".basename("") == "/"
698 # assert "".basename("") == ""
699 fun basename
(ext
: String): String
701 var l
= length
- 1 # Index of the last char
702 while l
> 0 and self.chars
[l
] == '/' do l
-= 1 # remove all trailing `/`
703 if l
== 0 then return "/"
704 var pos
= chars
.last_index_of_from
('/', l
)
707 n
= substring
(pos
+1, l-pos
)
709 return n
.strip_extension
(ext
)
712 # Extract the dirname of a path
714 # assert "/path/to/a_file.ext".dirname == "/path/to"
715 # assert "path/to/a_file.ext".dirname == "path/to"
716 # assert "path/to".dirname == "path"
717 # assert "path/to/".dirname == "path"
718 # assert "path".dirname == "."
719 # assert "/path".dirname == "/"
720 # assert "/".dirname == "/"
721 # assert "".dirname == "."
724 var l
= length
- 1 # Index of the last char
725 while l
> 0 and self.chars
[l
] == '/' do l
-= 1 # remove all trailing `/`
726 var pos
= chars
.last_index_of_from
('/', l
)
728 return substring
(0, pos
)
729 else if pos
== 0 then
736 # Return the canonicalized absolute pathname (see POSIX function `realpath`)
737 fun realpath
: String do
738 var cs
= to_cstring
.file_realpath
739 var res
= cs
.to_s_with_copy
740 # cs.free_malloc # FIXME memory leak
744 # Simplify a file path by remove useless ".", removing "//", and resolving ".."
746 # * ".." are not resolved if they start the path
747 # * starting "/" is not removed
748 # * trailing "/" is removed
750 # Note that the method only work on the string:
752 # * no I/O access is performed
753 # * the validity of the path is not checked
756 # assert "some/./complex/../../path/from/../to/a////file//".simplify_path == "path/to/a/file"
757 # assert "../dir/file".simplify_path == "../dir/file"
758 # assert "dir/../../".simplify_path == ".."
759 # assert "dir/..".simplify_path == "."
760 # assert "//absolute//path/".simplify_path == "/absolute/path"
761 # assert "//absolute//../".simplify_path == "/"
763 fun simplify_path
: String
765 var a
= self.split_with
("/")
766 var a2
= new Array[String]
768 if x
== "." then continue
769 if x
== "" and not a2
.is_empty
then continue
770 if x
== ".." and not a2
.is_empty
and a2
.last
!= ".." then
776 if a2
.is_empty
then return "."
777 if a2
.length
== 1 and a2
.first
== "" then return "/"
781 # Correctly join two path using the directory separator.
783 # Using a standard "{self}/{path}" does not work in the following cases:
786 # * `path` starts with `'/'`.
788 # This method ensures that the join is valid.
790 # assert "hello".join_path("world") == "hello/world"
791 # assert "hel/lo".join_path("wor/ld") == "hel/lo/wor/ld"
792 # assert "".join_path("world") == "world"
793 # assert "hello".join_path("/world") == "/world"
794 # assert "hello/".join_path("world") == "hello/world"
795 # assert "hello/".join_path("/world") == "/world"
797 # Note: You may want to use `simplify_path` on the result.
799 # Note: This method works only with POSIX paths.
800 fun join_path
(path
: String): String
802 if path
.is_empty
then return self
803 if self.is_empty
then return path
804 if path
.chars
[0] == '/' then return path
805 if self.last
== '/' then return "{self}{path}"
806 return "{self}/{path}"
809 # Convert the path (`self`) to a program name.
811 # Ensure the path (`self`) will be treated as-is by POSIX shells when it is
812 # used as a program name. In order to do that, prepend `./` if needed.
814 # assert "foo".to_program_name == "./foo"
815 # assert "/foo".to_program_name == "/foo"
816 # assert "".to_program_name == "./" # At least, your shell will detect the error.
817 fun to_program_name
: String do
818 if self.has_prefix
("/") then
825 # Alias for `join_path`
827 # assert "hello" / "world" == "hello/world"
828 # assert "hel/lo" / "wor/ld" == "hel/lo/wor/ld"
829 # assert "" / "world" == "world"
830 # assert "/hello" / "/world" == "/world"
832 # This operator is quite useful for chaining changes of path.
833 # The next one being relative to the previous one.
837 # var c = "baz/foobar"
838 # assert a/b/c == "/bar/baz/foobar"
839 fun /(path
: String): String do return join_path
(path
)
841 # Returns the relative path needed to go from `self` to `dest`.
843 # assert "/foo/bar".relpath("/foo/baz") == "../baz"
844 # assert "/foo/bar".relpath("/baz/bar") == "../../baz/bar"
846 # If `self` or `dest` is relative, they are considered relatively to `getcwd`.
848 # In some cases, the result is still independent of the current directory:
850 # assert "foo/bar".relpath("..") == "../../.."
852 # In other cases, parts of the current directory may be exhibited:
854 # var p = "../foo/bar".relpath("baz")
855 # var c = getcwd.basename("")
856 # assert p == "../../{c}/baz"
858 # For path resolution independent of the current directory (eg. for paths in URL),
859 # or to use an other starting directory than the current directory,
860 # just force absolute paths:
862 # var start = "/a/b/c/d"
863 # var p2 = (start/"../foo/bar").relpath(start/"baz")
864 # assert p2 == "../../d/baz"
867 # Neither `self` or `dest` has to be real paths or to exist in directories since
868 # the resolution is only done with string manipulations and without any access to
869 # the underlying file system.
871 # If `self` and `dest` are the same directory, the empty string is returned:
873 # assert "foo".relpath("foo") == ""
874 # assert "foo/../bar".relpath("bar") == ""
876 # The empty string and "." designate both the current directory:
878 # assert "".relpath("foo/bar") == "foo/bar"
879 # assert ".".relpath("foo/bar") == "foo/bar"
880 # assert "foo/bar".relpath("") == "../.."
881 # assert "/" + "/".relpath(".") == getcwd
882 fun relpath
(dest
: String): String
885 var from
= (cwd
/self).simplify_path
.split
("/")
886 if from
.last
.is_empty
then from
.pop
# case for the root directory
887 var to
= (cwd
/dest
).simplify_path
.split
("/")
888 if to
.last
.is_empty
then to
.pop
# case for the root directory
890 # Remove common prefixes
891 while not from
.is_empty
and not to
.is_empty
and from
.first
== to
.first
do
896 # Result is going up in `from` with ".." then going down following `to`
897 var from_len
= from
.length
898 if from_len
== 0 then return to
.join
("/")
899 var up
= "../"*(from_len-1
) + ".."
900 if to
.is_empty
then return up
901 var res
= up
+ "/" + to
.join
("/")
905 # Create a directory (and all intermediate directories if needed)
907 # Return an error object in case of error.
909 # assert "/etc/".mkdir != null
910 fun mkdir
: nullable Error
912 var dirs
= self.split_with
("/")
913 var path
= new FlatBuffer
914 if dirs
.is_empty
then return null
915 if dirs
[0].is_empty
then
916 # it was a starting /
919 var error
: nullable Error = null
921 if d
.is_empty
then continue
924 var res
= path
.to_s
.to_cstring
.file_mkdir
925 if not res
and error
== null then
926 error
= new IOError("Cannot create directory `{path}`: {sys.errno.strerror}")
932 # Delete a directory and all of its content, return `true` on success
934 # Does not go through symbolic links and may get stuck in a cycle if there
935 # is a cycle in the filesystem.
937 # Return an error object in case of error.
939 # assert "/fail/does not/exist".rmdir != null
940 fun rmdir
: nullable Error
942 var res
= to_path
.rmdir
943 if res
then return null
944 var error
= new IOError("Cannot change remove `{self}`: {sys.errno.strerror}")
948 # Change the current working directory
951 # assert getcwd == "/etc"
953 # assert getcwd == "/"
955 # Return an error object in case of error.
957 # assert "/etc".chdir == null
958 # assert "/fail/does no/exist".chdir != null
959 # assert getcwd == "/etc" # unchanger
960 fun chdir
: nullable Error
962 var res
= to_cstring
.file_chdir
963 if res
then return null
964 var error
= new IOError("Cannot change directory to `{self}`: {sys.errno.strerror}")
968 # Return right-most extension (without the dot)
970 # Only the last extension is returned.
971 # There is no special case for combined extensions.
973 # assert "file.txt".file_extension == "txt"
974 # assert "file.tar.gz".file_extension == "gz"
976 # For file without extension, `null` is returned.
977 # Hoever, for trailing dot, `""` is returned.
979 # assert "file".file_extension == null
980 # assert "file.".file_extension == ""
982 # The starting dot of hidden files is never considered.
984 # assert ".file.txt".file_extension == "txt"
985 # assert ".file".file_extension == null
986 fun file_extension
: nullable String
988 var last_slash
= chars
.last_index_of
('.')
989 if last_slash
> 0 then
990 return substring
( last_slash
+1, length
)
996 # Returns entries contained within the directory represented by self.
998 # var files = "/etc".files
999 # assert files.has("issue")
1001 # Returns an empty array in case of error
1003 # files = "/etc/issue".files
1004 # assert files.is_empty
1006 # TODO find a better way to handle errors and to give them back to the user.
1007 fun files
: Array[String] is extern import Array[String], Array[String].add
, NativeString.to_s
, String.to_cstring
`{
1011 dir_path = String_to_cstring( recv );
1012 if ((dir = opendir(dir_path)) == NULL)
1014 //perror( dir_path );
1016 Array_of_String results;
1017 results = new_Array_of_String();
1022 Array_of_String results;
1026 results = new_Array_of_String();
1028 while ( ( de = readdir( dir ) ) != NULL )
1029 if ( strcmp( de->d_name, ".." ) != 0 &&
1030 strcmp( de->d_name, "." ) != 0 )
1032 file_name = NativeString_to_s( strdup( de->d_name ) );
1033 Array_of_String_add( results, file_name );
1042 redef class NativeString
1043 private fun file_exists
: Bool is extern "string_NativeString_NativeString_file_exists_0"
1044 private fun file_stat
: NativeFileStat is extern "string_NativeString_NativeString_file_stat_0"
1045 private fun file_lstat
: NativeFileStat `{
1046 struct stat* stat_element;
1048 stat_element = malloc(sizeof(struct stat));
1049 res = lstat(recv, stat_element);
1050 if (res == -1) return NULL;
1051 return stat_element;
1053 private fun file_mkdir
: Bool is extern "string_NativeString_NativeString_file_mkdir_0"
1054 private fun rmdir
: Bool `{ return !rmdir(recv); `}
1055 private fun file_delete: Bool is extern "string_NativeString_NativeString_file_delete_0"
1056 private fun file_chdir: Bool is extern "string_NativeString_NativeString_file_chdir_0"
1057 private fun file_realpath: NativeString is extern "file_NativeString_realpath"
1060 # This class is system dependent ... must reify the vfs
1061 private extern class NativeFileStat `{ struct stat * `}
1062 # Returns the permission bits of file
1063 fun mode
: Int is extern "file_FileStat_FileStat_mode_0"
1064 # Returns the last access time
1065 fun atime
: Int is extern "file_FileStat_FileStat_atime_0"
1066 # Returns the last status change time
1067 fun ctime
: Int is extern "file_FileStat_FileStat_ctime_0"
1068 # Returns the last modification time
1069 fun mtime
: Int is extern "file_FileStat_FileStat_mtime_0"
1071 fun size
: Int is extern "file_FileStat_FileStat_size_0"
1073 # Returns true if it is a regular file (not a device file, pipe, sockect, ...)
1074 fun is_reg
: Bool `{ return S_ISREG(recv->st_mode); `}
1075 # Returns true if it is a directory
1076 fun is_dir: Bool `{ return S_ISDIR(recv->st_mode); `}
1077 # Returns true if it is a character device
1078 fun is_chr
: Bool `{ return S_ISCHR(recv->st_mode); `}
1079 # Returns true if it is a block device
1080 fun is_blk: Bool `{ return S_ISBLK(recv->st_mode); `}
1081 # Returns true if the type is fifo
1082 fun is_fifo
: Bool `{ return S_ISFIFO(recv->st_mode); `}
1083 # Returns true if the type is a link
1084 fun is_lnk: Bool `{ return S_ISLNK(recv->st_mode); `}
1085 # Returns true if the type is a socket
1086 fun is_sock
: Bool `{ return S_ISSOCK(recv->st_mode); `}
1089 # Instance of this class are standard FILE * pointers
1090 private extern class NativeFile `{ FILE* `}
1091 fun io_read
(buf
: NativeString, len
: Int): Int is extern "file_NativeFile_NativeFile_io_read_2"
1092 fun io_write
(buf
: NativeString, len
: Int): Int is extern "file_NativeFile_NativeFile_io_write_2"
1093 fun io_close
: Int is extern "file_NativeFile_NativeFile_io_close_0"
1094 fun file_stat
: NativeFileStat is extern "file_NativeFile_NativeFile_file_stat_0"
1095 fun fileno
: Int `{ return fileno(recv); `}
1096 # Flushes the buffer, forcing the write operation
1097 fun flush: Int is extern "fflush"
1098 # Used to specify how the buffering will be handled for the current stream.
1099 fun set_buffering_type(buf_length: Int, mode: Int): Int is extern "file_NativeFile_NativeFile_set_buffering_type_0"
1101 new io_open_read(path: NativeString) is extern "file_NativeFileCapable_NativeFileCapable_io_open_read_1"
1102 new io_open_write(path: NativeString) is extern "file_NativeFileCapable_NativeFileCapable_io_open_write_1"
1103 new native_stdin is extern "file_NativeFileCapable_NativeFileCapable_native_stdin_0"
1104 new native_stdout is extern "file_NativeFileCapable_NativeFileCapable_native_stdout_0"
1105 new native_stderr is extern "file_NativeFileCapable_NativeFileCapable_native_stderr_0"
1111 var stdin: PollableReader = new Stdin is protected writable, lazy
1114 var stdout: Writer = new Stdout is protected writable, lazy
1116 # Standard output for errors
1117 var stderr: Writer = new Stderr is protected writable, lazy
1119 # Enumeration for buffer mode full (flushes when buffer is full)
1120 fun buffer_mode_full: Int is extern "file_Sys_Sys_buffer_mode_full_0"
1121 # Enumeration for buffer mode line (flushes when a `\n
` is encountered)
1122 fun buffer_mode_line: Int is extern "file_Sys_Sys_buffer_mode_line_0"
1123 # Enumeration for buffer mode none (flushes ASAP when something is written)
1124 fun buffer_mode_none: Int is extern "file_Sys_Sys_buffer_mode_none_0"
1126 # returns first available stream to read or write to
1127 # return null on interruption (possibly a signal)
1128 protected fun poll( streams : Sequence[FileStream] ) : nullable FileStream
1130 var in_fds = new Array[Int]
1131 var out_fds = new Array[Int]
1132 var fd_to_stream = new HashMap[Int,FileStream]
1135 if s isa FileReader then in_fds.add( fd )
1136 if s isa FileWriter then out_fds.add( fd )
1138 fd_to_stream[fd] = s
1141 var polled_fd = intern_poll( in_fds, out_fds )
1143 if polled_fd == null then
1146 return fd_to_stream[polled_fd]
1150 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) `{
1151 int in_len
, out_len
, total_len
;
1152 struct pollfd
*c_fds
;
1155 int first_polled_fd
= -1;
1158 in_len
= Array_of_Int_length( in_fds
);
1159 out_len
= Array_of_Int_length( out_fds
);
1160 total_len
= in_len
+ out_len
;
1161 c_fds
= malloc
( sizeof
(struct pollfd
) * total_len
);
1164 for ( i
=0; i
<in_len
; i
++ ) {
1166 fd
= Array_of_Int__index( in_fds
, i
);
1169 c_fds
[i
].events
= POLLIN;
1172 /* output streams
*/
1173 for ( i
=0; i
<out_len
; i
++ ) {
1175 fd
= Array_of_Int__index( out_fds
, i
);
1178 c_fds
[i
].events
= POLLOUT;
1181 /* poll all fds
, unlimited timeout
*/
1182 result
= poll
( c_fds
, total_len
, -1 );
1185 /* analyse results
*/
1186 for ( i
=0; i
<total_len
; i
++ )
1187 if ( c_fds
[i
].revents
& c_fds
[i
].events
|| /* awaited event
*/
1188 c_fds
[i
].revents
& POLLHUP ) /* closed
*/
1190 first_polled_fd
= c_fds
[i
].fd
;
1194 return Int_as_nullable( first_polled_fd
);
1196 else if ( result
< 0 )
1197 fprintf
( stderr
, "Error in Stream:poll: %s\n", strerror
( errno
) );
1204 # Print `objects
` on the standard output (`stdout
`).
1205 fun printn(objects: Object...)
1207 sys.stdout.write(objects.to_s)
1210 # Print an `object
` on the standard output (`stdout
`) and add a newline.
1211 fun print(object: Object)
1213 sys.stdout.write(object.to_s)
1214 sys.stdout.write("\n")
1217 # Print `object
` on the error output (`stderr
` or a log system)
1218 fun print_error(object: Object)
1220 sys.stderr.write object.to_s
1221 sys.stderr.write "\n"
1224 # Read a character from the standard input (`stdin
`).
1227 return sys.stdin.read_char.ascii
1230 # Read a line from the standard input (`stdin
`).
1233 return sys.stdin.read_line
1236 # Return the working (current) directory
1237 fun getcwd: String do return file_getcwd.to_s
1238 private fun file_getcwd: NativeString is extern "string_NativeString_NativeString_file_getcwd_0"