john pfeiffer
  • Home
  • Categories
  • Tags
  • Archives

word count

/* John Pfeiffer, Sun 23-Jun-07 for Bobby, updated 23dec07 */
/* a simple prog to count the number of chars, lines and words in a text file */

#include <stdio.h>
#include <stdlib.h>

#define CMDLINE_PARAMETERS 2

void program_usage_help( char* argv[] );
void test_commandline_parameters( int argc, char* argv[] );

int main(int argc, char* argv[])
{
    char c;
    int number_of_chars = 0, number_of_spaces=0, number_of_endlines=0, j=0;
    FILE* ifp;
    test_commandline_parameters( argc, argv );
    ifp = fopen(argv[1],"r");

    if( ifp == NULL )
    {    printf("error opening file/n");}
    else
    {

        do{     c = getc(ifp);
                if( c == ' ')
                {   number_of_spaces++;    
                    c = getc(ifp);
                    if( c > 48 && c < 123)      /* heuristic for word start */
                    {   j++;    }
                    else if( c == ' ' )
                    {   number_of_spaces++;    }
                    number_of_chars++;      /* we've grabbed an extra char to test */
                }
                else if( c == '\n')
                {   number_of_endlines++;   }

                number_of_chars++;
        }while( c!= EOF);

        fclose(ifp);
    }

    printf("There were %d chars in the file %s.\n",number_of_chars, argv[1]);
    printf("Approx %d lines in the file.\n",number_of_endlines+1);
    printf("Approx %d words in the file.\n",number_of_spaces+1);    
    printf("More accurate heuristic says approx %d words.\n",j);

/*  c = ' ';
    printf("%c,%d\n",c,c);      32 == space

    for( i=48; i<123; i++)      from 0 -> z
    { printf("%c ",i);
    }
    getchar();                   */

    return 0;
}

void program_usage_help( char* argv[] )
{   printf("%s filename.txt",argv[0]); 
}/* end program_usage_help */

void test_commandline_parameters( int argc, char* argv[] )
{   int i = 0;
    if( argc < CMDLINE_PARAMETERS )
    {   printf("\nMore parameters needed, e.g.\n"); 
        program_usage_help( argv );
        exit(1);
    }
    else if( argc > CMDLINE_PARAMETERS )
    {   printf("\nToo many command line parameters, e.g.\n");   
        program_usage_help( argv );
        exit(1);
    }
    else
    {   while( i < argc )
        {   printf("%s ", argv[i]);     
            i++;
        }
        printf("in progress...\n\n");
    }

}/* end test_commandline_paramters func */

  • « execute time testing
  • win basic with comments »

Published

Jun 23, 2007

Category

c

~210 words

Tags

  • c 95
  • count 6
  • word 3