File Reads and Writes

This article shows examples of file handling facilities in Fortress used in the this program: trunk/ProjectFortress/demos/tennisRanking.fss.

In order to use FileReadStream and FileWriteStream, trunk/Library/File.fsi must be imported:

Loading...

The run function takes arguments from the command line:

Loading...

and if the arguments are not appropriate, it prints the usage message:

Loading...

Files can be opened for reads and writes by FileReadStream and FileWriteStream, respectively:

Loading...

and they must be closed before ending the program:

Loading...

The readLine method defined in FileReadStream returns the next available line from the stream (discarding line termination characters) and returns "" on EOF:

Loading...

The example program defines two helper functions to read words from the stream:

Loading...

Any Unicode characters can be read and written by the file stream utilities. For example, a sample input file trunk/ProjectFortress/demos/tennisGames includes Korean characters:

...
begin
양소림  고아라  오채린  송은희
양소림  고아라  송은희  진선영
박승찬  변재섭
박승찬  송은희  지현수  양소림
...

and a sample output file trunk/ProjectFortress/demos/tennis050307 includes Korean characters:

...
Invalid game: 박승찬/오형식 vs 기철수/오왕열 has 32 ranking differences.
Invalid game: 지현수 vs 변재섭 has played before.

May 03, 2007

순위  선수         승패            경기수            포인트
-------------------------------------------------------------------
 1  김종성    26 / 15 (3 / 1)      41 (4)       2870 (130)
 2  기철수    40 / 34 (5 / 7)      74 (12)       2785 (130)
 3  오왕열    34 / 20 (6 / 1)      54 (7)       2610 (310)
 4  박승찬    13 / 5 (7 / 1)      18 (8)       2425 (1025)
...

One frequently asked question is how to convert a string to an integer value. trunk/Library/FortressLibrary.fss defines strToInt for this functionality:

Loading...

Finally, print is a varargs method that writes characters to the end of a FileStream:

Loading...

and println is a varargs method that writes characters to the end of a FileStream, but in addition appends a final newline character "\n" at the same time.