#include <fstream.h> #include <stdio.h> #include "ast.h" #include "parser.h" #include "scanner.h"
StarFileNode *AST; // StarFileNode is defined in "ast.h" ofstream *os; // ofstream is in the standard libc++.
*AST
is a pointer that will be filled
by the parser when it reads a star file into memory. Due
to the limitations of lex/yacc parsers, such a global
variable must be used. If you wish to read more than one
star file, you will need to read the first star file into
the AST variable, then copy it to another StarFileNode using
the StarFileNode's copy constructor, then read the next file
into the AST variable. Also note that since AST is a pointer,
the it is up to you to delete the space (delete AST;
)
when done with it.
*os
is a pointer to a C++ output stream.
This is used by the Unparse()
function.
Unparse()
is a method that will write out
the STAR file in memory (or just a portion of it) to a
file. Unparse() is hardwired to write its output to the
stream called (*os)
. Therefore, to decide
where the file is to be written to, you open the
*os
file yourself before calling Unparse()
. NOTE: One common mistake has been for
people to forget to close the (*os)
output stream,
and therefore the last lines of output never flush into the
file.
yyin
is not something that you need to
put in your global variables section, but it is included
as part of the parser. The parser that reads in a STAR file
will read it from the file yyin
. yyin
is an Ansii C (FILE *
) file. You are expected
to open this file before calling yyparse()
, so
that yyparse()
knows what file to parse.
This code will parse in a star file called "input.star", and write it out under the name "output.star". The example doesn't do anything else, but you can use it as a skeleton from which to base your own code.
Don't be overwhelmed if you don't understand everything here, but
you should be able to understand the use of *os
,
*AST
, and yyin
.
#include <fstream.h> #include <stdio.h> #include "ast.h" #include "parser.h" #include "scanner.h" StarFileNode *AST; // StarFileNode is defined in "ast.h" ofstream *os; // ofstream is in the standard libc++. int main( void ) { yyin = fopen( "input.star", "r" ); if( yyin == NULL ) { cerr << "Error opening input.star\n"; return 2; } if( yyparse() == 0 ) // yyparse returns nonzero on error. { // It was successfully parsed, now *AST contains the // file in memory. For this simple example, we will // just Unparse it right away and quit. // ------------------------------------------------- os = new ofstream( "output.star" ); if( os == NULL ) { cerr << "Error opening output.star\n"; return 1; } AST->Unparse(0); // Unparse takes 1 arg: the indent level: delete os; // C++ streams are closed by calling the delete // operator. If you do not close it, it might // not flush the last line or two of the output. delete AST; } else { cerr << "Syntax error while parsing file.\n"; return 3; } return 0; }