A friend called me the other day and wanted a quick program
that could count the number of specific words in a file. This
program will enumerate through any .txt file and count the
specific words that you would like to keep track of. In this case
the files he wanted to enumerate through were phone records to see
how many calls were work, home or cell related from a report that
was generated daily. There isn't anything new here except a new
function you can research.
strtok( );
You can drag and drop the file onto the .exe or use the
command prompt :)
wordsearch.exe filename
__________________________________________________________
#define _CRT_SECURE_NO_DEPRECATE
#include <string.h>
#include <stdio.h>
#include <conio.h>
#include <shlobj.h>
//pointer to our string
char *currentword;
int main(int argc,char *pArgv[])
{
char sourceName[260];
char readfile[256];
int result1;
int result2;
int result3;
//set counts to zero
int count1 = 0;
int count2 = 0;
int count3 = 0;
if (argc==2)
{
//This takes the filename of the file that
//you drag onto the exe and copies the name
//to sourceName
strcpy( sourceName, pArgv[1] );
FILE *pFile = fopen( sourceName, "r" );
if( pFile == 0 )
{
printf( "\n\nFile does not exist in this directory." );
}
else
{
while ( fgets( readfile, 256, pFile ) )
{
currentword = strtok( readfile, " ,\t\n" );
//while there are still words to look through
while( currentword != NULL )
{
//compare the word "Work" with the current word to
//see if they are the same
result1 = strcmpi( currentword,"Work" );
//compare the word "Cell" with the current word to
//see if they are the same
result2 = strcmpi( currentword,"Cell" );
//compare the word "Home" with the current word to
//see if they are the same
result3 = strcmpi( currentword,"Home" );
//if a "Work" match increment by one
if( result1 == 0 )
{
count1++;
}
//if a "Cell" match increment by one
else if( result2 == 0 )
{
count2++;
}
//if a "Home" match increment by one
else if( result3 == 0 )
{
count3++;
}
//go to the next word to continue search
currentword = strtok( NULL, " ,\t\n" );
}
}
//close our file
fclose( pFile );
//print out the summary for the three searches
printf( "\n %d Work references\n\n",count1 );
printf( " %d Cell references\n\n",count2 );
printf( " %d Home references\n\n",count3 );
_getch();
}
}
else
{
//if you double click the exe it will print this
printf("\n\n Please drag and drop your file on the exe.\n\n ");
printf("Press enter to exit this screen. ");
_getch();
}
return 0;
}