Hi,
I'm trying to write a program for the number of occerrence of a word from a file,
so I need to open a user input file as argv[1] and get the search word from argv[2] and print out the number of occerrence of that word.
can someone help me please.
Code:
#include <stdio.h>
#include <ctype.h>
#include <stdafx.h>
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <string.h>
int process_file( FILE *fp );
int _tmain(int argc, _TCHAR* argv[])
{
if ( argc > 1 ) {
FILE *fp = fopen( argv[1], "r" );
if ( fp ) {
if ( !process_file( fp ) ) {
// failure means a stream error or bad file
perror( "error reading from the file" );
}
fclose( fp );
} else {
perror( "error opening the file" );
}
} else {
fprintf( stderr, "usage: prog <filename>\n" );
}
return 0;
}
int process_file( FILE *fp ) {
char buff[1000]={0},
tempStr[300]={0},
*tokenPtr;
int n = 0;
while ( fgets( tempStr, sizeof tempStr, fp ) != NULL ) {
strcat( buff, tempStr );
}
tokenPtr = strtok( buff, ". !, \n" );
do {
n=strcmp (tokenPtr,argv[2]);
n++;
}while ( tokenPtr != NULL );
tokenPtr = strtok( NULL, " ! -.,\n" );
printf( "%8s%15s\n", "searched Word", "Occurrences" );
printf("%4c%4d",argv[2],n);
}