Advertisement
Kimossab

SO P1 - Turno 1 V2

Mar 16th, 2015
295
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.15 KB | None | 0 0
  1. #include <unistd.h>
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include <string.h>
  5.  
  6. #define exit_on_null(s,m) if(s == NULL) { perror(m); exit(1); }
  7.  
  8. //print f
  9.  
  10. char procurarstring(char *a, char *b)
  11. {
  12. if(!b[0] || !a[0])
  13. return 0;
  14. char *c;
  15. for(;;)
  16. {
  17. if(!*a)
  18. break;
  19. c=a;
  20. for(;;)
  21. {
  22. if(!*b)
  23. return 1;
  24. if(*c++ != *b++)
  25. break;
  26. }
  27. b-=(int)c;
  28. b+=(int)a;
  29. a++;
  30. }
  31. return 0;
  32. }
  33.  
  34. int linhas(FILE *f, char *str)
  35. {
  36. char *line = NULL;
  37. ssize_t n=0;
  38. int l=0;
  39. while((n = getline(&line, &n, f)) != -1)
  40. if(procurarstring(line,str))
  41. l++;
  42. if(line) free(line);
  43. return l;
  44. }
  45.  
  46.  
  47. int main (int argc, char *argv[])
  48. {
  49. FILE *fp;
  50. int c;
  51. char *value;
  52. /* Usage */
  53. if (argc<=1)
  54. {
  55. printf("Usage: %s <file name> <flags>\n",argv[0]);
  56. exit(1);
  57. }
  58. fp=fopen(argv[1],"r");/*Abre ficheiro para leitura*/
  59. exit_on_null(fp,"Erro na abertura");
  60. /*Leitura linha a linha*/
  61. while((c=getopt(argc,argv,":l:"))!=-1)
  62. {
  63. fseek(fp,0,SEEK_SET);
  64. switch(c)
  65. {
  66. case 'l': value = optarg;
  67. break;
  68. }
  69. }
  70. printf("%d linhas (com a palavra %s)\n",linhas(fp,value), value);
  71. fclose(fp);
  72. return 0;
  73. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement