| 1 |
//--------------------------------------------------------------------- |
| 2 |
// name: read-tokens.ck |
| 3 |
// desc: this example shows how to: |
| 4 |
// 1) open a text file for reading |
| 5 |
// 2) read the file line by line |
| 6 |
// 3) for each line, tokenize it into words (separated by spaces) |
| 7 |
// |
| 8 |
// author: Ge Wang (https://ccrma.stanford.edu/~ge/) |
| 9 |
// date: Winter 2023 |
| 10 |
//--------------------------------------------------------------------- |
| 11 |
|
| 12 |
// path and name of file to read |
| 13 |
me.dir() + "jabberwocky.txt" => string filename; |
| 14 |
// or get filename from command line arguments, if any |
| 15 |
if( me.args() > 0 ) me.arg(0) => filename; |
| 16 |
|
| 17 |
// delay between words (for effect) |
| 18 |
50::ms => dur WORD_T; |
| 19 |
// delay between lines |
| 20 |
800::ms => dur LINE_T; |
| 21 |
|
| 22 |
// instantiate a file IO object |
| 23 |
FileIO fio; |
| 24 |
// a string tokenizer |
| 25 |
StringTokenizer tokenizer; |
| 26 |
// a line of text |
| 27 |
string line; |
| 28 |
// a word token |
| 29 |
string word; |
| 30 |
|
| 31 |
// open the file |
| 32 |
fio.open( filename, FileIO.READ ); |
| 33 |
|
| 34 |
// ensure it's ok |
| 35 |
if( !fio.good() ) |
| 36 |
{ |
| 37 |
cherr <= "can't open file: " <= filename <= " for reading..." |
| 38 |
<= IO.newline(); |
| 39 |
me.exit(); |
| 40 |
} |
| 41 |
|
| 42 |
// new line |
| 43 |
cherr <= IO.newline(); |
| 44 |
|
| 45 |
// loop until end |
| 46 |
while( fio.more() ) |
| 47 |
{ |
| 48 |
// read current line |
| 49 |
fio.readLine() => line; |
| 50 |
// for each line, tokenize |
| 51 |
tokenizer.set( line ); |
| 52 |
// loop over tokens |
| 53 |
while( tokenizer.more() ) |
| 54 |
{ |
| 55 |
// get the next word |
| 56 |
tokenizer.next() => word; |
| 57 |
// print word followed by a space |
| 58 |
cherr <= word <= " "; |
| 59 |
// delay for effect |
| 60 |
WORD_T => now; |
| 61 |
} |
| 62 |
// done with current line |
| 63 |
cherr <= IO.newline(); |
| 64 |
// delay for effect |
| 65 |
LINE_T => now; |
| 66 |
} |