tokenizing file parser example

By: Anthony Pryor

Abstract: simple file parser example


#include <iostream.h>
#include <fstream.h>
#include <string.h>

int main(int argc, char ** argv)
{

argc = 4;

argv[0] = "inputf.txt";
argv[1] = "outputf.txt";
argv[2] = "this";
argv[3] = "bunny";

if(argc > 3)
	{

	ifstream infile(argv[0]);
	ofstream outfile(argv[1]);
	char * search = argv[2];
	char * replace = argv[3];
	char * linebuf = new char[100];
	char * tempbuf = new char[100];
	char * lastTok = new char[100];

		 char outBuf[100] = "";
		// char tokbuf[100]= "";


	do
		 {
		      infile.getline(linebuf, 100);
		      if(linebuf != NULL)
				{
				do   {
					strcpy(tempbuf, linebuf);
					lastTok = strtok(tempbuf, " ");

					if(strlen(linebuf) > strlen(lastTok))
					  strcpy( linebuf , (linebuf + strlen(lastTok) ) + 1);
					if((lastTok != NULL) && (strcmp(lastTok, search) != 0))
						{
						strcat(outBuf, lastTok);
						if(strlen(linebuf) > strlen(lastTok))
						strcat(outBuf, " ");
					        }
					        else if((lastTok != NULL) && (strcmp(lastTok, search) == 0))
						 {
						 strcat(outBuf, replace);

						 strcat(outBuf, " ");

						 }
						 if(! (strlen(linebuf) > strlen(lastTok)) )
						{
						strnset( linebuf, '0', 100);
						strnset( tempbuf, '0', 100);
						}

				      }
				      while(lastTok != NULL);

				outfile << outBuf <<endl;

				outBuf[0] = '0';
				  }
			else linebuf[0] = '0';

		 }
	while ( ! infile.eof());

	delete linebuf;
	delete tempbuf;
	delete lastTok;
	}
else cout << "nArguments not specified.nUse:  parser    n";

return 0;

}



//inputf.txt:
hi my name is xyzzy
as you can see the point of this simple parser is to find
and replace a given string wherever it appears in this file
the output file should have this exact message
except that the word this will have been replaced with whatever
you specify to see this in action comment out internal
param specifiers rebuild and
type the following at the command line
parser inputf.txt outputf.txt this bunny

Server Response from: ETNASC03