Example 1. This simple program creates a new file and writes a string
to it.
#include <pstreams.h>
USING_PTYPES
int main()
{
// the outfile object is declared and constructed outside
// the try...catch clause, since the exception object
// contains a reference to the stream that caused the error.
// besides, stream constructors and destructors in PTypes
// never throw exceptions.
outfile f(fname);
f.set_bufsize(1024); // the default value in this version is 8192
try
{
f.open();
f.put("This is a test file.");
f.close();
}
catch (estream* e)
{
perr.putf("File error: %s\n", e->get_message());
delete e;
}
return 0;
}
Example 2. This program reads a C source, extracts identifiers and builds
a usage dictionary. It does not understand C comments and strings though, but
can be easily improved to understand them too.
#include <ptypes.h>
#include <pstreams.h>
USING_PTYPES
const cset letters("_A-Za-z");
const cset digits("0-9");
const cset identchars = letters + digits;
const cset otherchars = !letters;
void main(int argc, char* argv[])
{
strlist dic(SL_SORTED);
infile f(argv[1]);
try
{
f.open();
while (!f.get_eof())
{
char c = f.preview();
// a C identifier begins with a letter
if (c & letters)
{
// ... and may contain letters and digits
string ident = f.token(identchars);
int i;
if (!search(dic, ident, i))
add(dic, ident, 0);
}
else
// ignore everything else
f.skiptoken(otherchars);
}
}
catch (estream* e)
{
pout.putf("Error: %s\n", e->get_message());
delete e;
}
// now print the dictionary
for (int i = 0; i < length(dic); i++)
pout.putline(getstr(dic, i));
}