[antlr-interest] simple function exercise

Sohail Somani sohail at taggedtype.net
Mon Oct 17 21:56:10 PDT 2005


On Mon, 2005-17-10 at 21:23 -0700, eric nelson wrote:
> Why do you say "make sure you work with streams, not files"?
> Eventually I'd like to actually be able to have the new source code in
> a new file.  Thanks for your response!  - e

Streams are a useful abstraction. It means you can use the same code to
write to a file, write to a network connection or write to a screen.

You don't lose anything much by working with streams.

For example (C++, my java isn't so hot, perhaps the c++ isn't either :D)

#include <iostream>
#include <fstream>

using namespace std;

void func(std::ostream & os)
{
        os << "output" << endl;
        os << "... more complicated stuff" << endl;
        os << "done" << endl;
}

int main(int argc, char * argv[])
{
        if (argc==1)
        {
                func(cout); // write to console
        }
        else if (argc==2)
        {
                ofstream file(argv[1]);
                func(file); // else write to file
        }
}

Witness the output:

pundai at dev:~/tmp$ ./a.out # writes to console
output
... more complicated stuff
done
pundai at dev:~/tmp$ ./a.out file # writes to file named as first argument
pundai at dev:~/tmp$ cat file
output
... more complicated stuff
done

Sohail



More information about the antlr-interest mailing list