write a c program,(i am using linux system,so that would be better if i can run
ID: 667063 • Letter: W
Question
write a c program,(i am using linux system,so that would be better if i can run it on Linux),which can read a (sub)string on the command line and search the string in a file called "words". For example in this file, there are many words : fantastic; dog; antx; xant; bchhnttntha. if i input a string lets say 'nt', after the program running, the result should be: antx,xant,bchhnttntha which these words contain string 'nt'. However if there is no match(include input string :123 etc.), a note 'No match found' should be printed.
Like this one:
-> ./match 123 < words
-> No match found.
If usage is incorrect, a note should also be printed like these two below:
case 1: -> ./match < words
-> Usage:./match string
case 2: -> ./match bull ant < words
-> Usage:./match string
Thanks in advance.
Explanation / Answer
#include <stdio.h>
int main( int argc, char *argv[] )
{
printf("Program name %s ", argv[0]);
char str[999];
FILE * file;
int result;
if( argc > 4 || argc < 4)
{
printf("Usage:./match string ");
}
else
{
file = fopen( argv[3] , "r");
if (file) {
while (fscanf(file, "%s", str)!=EOF)
{
if(strstr(str, argv[1]) != NULL){
printf("%s ",str);
}
}
fclose(file);
}
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.