Implements a means of reading and writing a generic file. Conduits
are the primary means of accessing external data, and File
extends the basic pattern by providing file-specific methods to
set the file size, seek to a specific file position and so on.
Serial input and output is straightforward. In this example we
copy a file directly to the console:
1
2
3
4
5
|
// open a file for reading
auto from = new File ("test.txt");
// stream directly to console
Stdout.copy (from);
|
And here we copy one file to another:
1
2
3
4
5
6
7
8
9
|
// open file for reading
auto from = new File ("test.txt");
// open another for writing
auto to = new File ("copy.txt", File.WriteCreate);
// copy file and close
to.copy.close;
from.close;
|
You can use InputStream.load() to load a file directly into memory:
1
2
3
|
auto file = new File ("test.txt");
auto content = file.load;
file.close;
|
Or use a convenience static function within File:
1
|
auto content = File.get ("test.txt");
|
A more explicit version with a similar result would be:
1
2
3
4
5
6
7
8
9
|
// open file for reading
auto file = new File ("test.txt");
// create an array to house the entire file
auto content = new char [file.length];
// read the file content. Return value is the number of bytes read
auto bytes = file.read (content);
file.close;
|
Conversely, one may write directly to a File like so:
1
2
3
4
5
|
// open file for writing
auto to = new File ("text.txt", File.WriteCreate);
// write an array of content to it
auto bytes = to.write (content);
|
There are equivalent static functions, File.set() and
File.append(), which set or append file content respectively.
File can happily handle random I/O. Here we use seek() to
relocate the file pointer:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
// open a file for reading and writing
auto file = new File ("random.bin", File.ReadWriteCreate);
// write some data
file.write ("testing");
// rewind to file start
file.seek (0);
// read data back again
char[10] tmp;
auto bytes = file.read (tmp);
file.close;
|
Note that File is unbuffered by default - wrap an instance within
tango.io.stream.Buffered for buffered I/O.
Compile with -version=Win32SansUnicode to enable Win95 & Win32s file
support.