[Code example] Find pattern -x-n page 117

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

Find pattern -x-n page 117

Post by BJT » Wed May 03, 2017 11:44 pm

  1. #include <stdio.h>
  2. #include <string.h>
  3.  
  4. #define MAXLINE 1000
  5. size_t getline(char *line, int max);
  6.  
  7. /* find: print lines that match pattern from 1st arg */
  8. int main(int argc, char *argv[])
  9. {
  10.     char line[MAXLINE];
  11.     long lineno = 0;
  12.     int c, except = 0, number = 0, found = 0;
  13.    
  14.     while (--argc > 0 && (*++argv)[0] == '-')
  15.         while (c = *++argv[0])
  16.             switch (c)
  17.             {
  18.                 case 'x':
  19.                     except = 1;
  20.                     break;
  21.                 case 'n':
  22.                     number = 1;
  23.                     break;
  24.                 default:
  25.                     printf("find: illegal option %c\n", c);
  26.                     argc = 0;
  27.                     found = -1;
  28.                     break;
  29.             }
  30.            
  31.     if (argc != 1)
  32.         printf("Usage: find -x -n pattern\n");
  33.     else
  34.         while (getline(line, MAXLINE) > 0)
  35.         {
  36.             lineno++;
  37.             if ((strstr(line, *argv) != NULL) != except)
  38.             {
  39.                 if (number)
  40.                     printf("%ld:", lineno);
  41.                 printf("%s\n", line);
  42.                 found++;
  43.             }
  44.         }
  45.     return found;
  46. }
  47.                
  48. size_t getline(char* f_line, int n)
  49. {
  50.     int c;
  51.     size_t size=(size_t)f_line;
  52.    
  53.     while(((size_t)f_line-size)<n && (c=getchar())!=EOF && c!='\n')
  54.         *f_line++=c;
  55.    
  56.     if(c=='\n')
  57.         *(f_line+1)=c;
  58.        
  59.     *(f_line)='\0';
  60.        
  61.     return (size_t)f_line-size;
  62. }    

Execute in console the binary file

Code: Select all

.c/ -x -n hello
Hello i am a program
1:Hello i am a program
hello people
nice time
3:nice time
word count: 201

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

Who is online

Users browsing this forum: No registered users and 1 guest