To contents Next section

2.2.1 save()

First we clone a Stdio.File program to the object o. Then we use it to open the file whose name is given in the string file_name for writing. We use the fact that if there is an error during opening, open() will return a false value which we can detect and act upon by exiting. The arrow operator (->) is what you use to access methods and variables in an object. If there is no error we use yet another control structure, foreach, to go through the mapping records one record at a time. We precede record names with the string "Record: " and song names with "Song: ". We also put every entry, be it song or record, on its own line by adding a newline to everything we write to the file.
Finally, remember to close the file.
void save(string file_name)
{
    string name, song;
    Stdio.File o=Stdio.File();

    if(!o->open(file_name,"wct"))
    {
        write("Failed to open file.\n");
        return;
    }

    foreach(indices(records),name)
    {
        o->write("Record: "+name+"\n");
        foreach(records[name],song)
            o->write("Song: "+song+"\n");
    }

    o->close();
}

To contents Next section