[Code example] Example grep recieve argv page 116

User avatar

Topic author
BJT
Site Admin
Site Admin
Posts: 141
Joined: Thu Apr 20, 2017 4:43 pm
Instruction: University Student
Gender:
Age: 27
Venezuela

Example grep recieve argv page 116

Post by BJT » Wed May 03, 2017 7:51 pm

  1. #include <stdio.h>
  2. #include <string.h>
  3.  
  4. #define MAXLINE 1000
  5.  
  6. size_t getline(char* f_line, int n);
  7.  
  8. /* find: print lines that match pattern from 1st arg */
  9. int main(int argc, char *argv[])
  10. {
  11.     char line[MAXLINE];
  12.     int found = 0;
  13.    
  14.     if (argc != 2)
  15.         printf("Usage: find pattern\n");
  16.     else
  17.         while (getline(line, MAXLINE) > 0)
  18.             if (strstr(line, argv[1]) != NULL)
  19.             {
  20.                 printf("%s", line);
  21.                 found++;
  22.             }
  23.    
  24.     return found;
  25. }
  26.                
  27. size_t getline(char* f_line, int n)
  28. {
  29.     int c;
  30.     size_t size=(size_t)f_line;
  31.    
  32.     while(((size_t)f_line-size)<n && (c=getchar())!=EOF && c!='\n')
  33.         *f_line++=c;
  34.    
  35.     if(c=='\n')
  36.         *(f_line+1)=c;
  37.        
  38.     *(f_line)='\0';
  39.        
  40.     return (size_t)f_line-size;
  41. }        


Execute in console the binary file

Code: Select all

.c/ Hello
output

Code: Select all

Hello i am program
Hello i am program
word count: 143

Link:
BBcode:
HTML:
Hide post links
Show post links

Who is online

Users browsing this forum: No registered users and 1 guest