In: Computer Science
Write a C program to find the count of words and optionally the longest and or shortest words in a string input by the user or coming from a file. If there is no filename the user would enter the string right after running the command. You must use getopt to parse the command line.
Usage: words [-l] [-s] [filename]
The l flag means to find the longest and the s option means to find the shortest. You may have both or one of the flags. Output should be well formatted and easy to read.
Code should be nicely indented and commented.
Create a simple Makefile to compile your program into an executable called words.
You should submit the source code and your Makefile. The Makefile should be called Makefile with no extension. I should be able to type make at the command line to compile your program. Do not include any other files or folders in the zipfile. This applies even if you are a Mac user.
Here is the code for your question. Also attached is the screen shot of compiling and running the program with different options . A file test.txt was used and its contents displayed in the output. Please do rate the answer if you are happy with its working
#include <stdio.h>
#include <unistd.h>
#include <string.h>
int main(int argc,char **argv)
{
int lflag=0,sflag=0;
char filename[256]="\0",line[256];
FILE *file;
int
start=0,end,word_len,max=0,min=0,long_words=0,short_words=0,total=0;
int c,index;
while ((c = getopt (argc, argv, "ls")) != -1)
switch (c)
{
case 'l':
lflag = 1;
break;
case 's':
sflag = 1;
break;
}
for (index = optind; index < argc; index++)
{
//printf("%s",argv[index]);
strcpy(filename, argv[index]);
break;
}
if(filename[0]=='\0')
{
printf("Enter a line:");
//get a line from stdin max length 256
fgets(line,256,stdin);
}
else
{
file=fopen(filename,"r");
fgets(line,256,file);
}
//printf("%s",line);
while(line[start]!='\0')
{
//skip over all space characters to find a new word beginning
while(line[start]==' ' || line[start]=='\t' ||
line[start]=='\n')
{
start++;
}
end=start;
//find a space character to figure out word end
while(line[end]!=' ' && line[end]!='\t' &&
line[end]!='\0' && line[end]!='\n')
{
end++;
}
word_len=end-start;
if(word_len==0) /*if start and end are same, i.e on '\0'*/
break;
if(lflag)
{
if(word_len>max) /*if the new word is bigger than older
longest*/
{
max=word_len;
long_words=1;
}
else if(word_len==max) /*if the word is same length as longest so
far, increase count*/
long_words++;
}
if(sflag)
{
if(min==0 || word_len<min) /*if this is new shortest
word*/
{
min=word_len;
short_words=1;
}
else if(word_len==min) /*found another shortest word*/
short_words++;
}
//printf("max:%d min:%d",max,min);
total++;
start=end;
}
printf("\n Total No. of words : %d",total);
if(lflag)
printf("\n Longest length is %d. No. of long words :%d",max,long_words);
if(sflag)
printf("\n Shortest length is %d. No. of short words
:%d",min,short_words);
}
