Advertisement
Kimossab

Get Lines/Chars/Word from a file (teste on Ubuntu)

Mar 10th, 2015
268
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.60 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. int linhas(FILE *f)
  9. {
  10.     char *line = NULL;
  11.     ssize_t n=0;
  12.     int l=0;
  13.         while((n = getline(&line, &n, f)) != -1)
  14.         {
  15.         l++;
  16.         }
  17.     if(line) free(line);
  18.     return l;
  19. }
  20.  
  21. int words(FILE *f)
  22. {
  23.         char *line = NULL;
  24.         ssize_t n=0;
  25.         int w=0, i;
  26.     char flag=0;
  27.         while((n = getline(&line, &n, f)) != -1)
  28.         {
  29.         i=0;
  30.         while(line[i] != '\0')
  31.         {
  32.             if(line[i] == ' ' && flag)
  33.             {
  34.                 w++;
  35.                 flag=0;
  36.             }
  37.             else if(line[i] != ' ' && !flag)
  38.                 flag = 1;
  39.             i++;
  40.         }
  41.         if(flag)
  42.         {
  43.             w++;
  44.             flag = 0;
  45.         }
  46.         }
  47.         if(line) free(line);
  48.         return w;
  49. }
  50.  
  51. int chars(FILE *f)
  52. {
  53.         char *line = NULL;
  54.         ssize_t n=0;
  55.         int c=0;               
  56.         while((n = getline(&line, &n, fp)) != -1)
  57.             count+=strlen(line)-1;
  58.         if(line) free(line);
  59.         return c;
  60. }
  61.  
  62.  
  63. int main (int argc, char *argv[])
  64. {
  65.     FILE *fp;
  66.     int c;
  67.     /* Usage */
  68.     if (argc<=2)
  69.     {
  70.         printf("Usage: %s <file name>\n",argv[0]);
  71.         exit(1);
  72.     }
  73.     fp=fopen(argv[1],"r");/*Abre ficheiro para leitura*/
  74.     exit_on_null(fp,"Erro na abertura");
  75.     /*Leitura linha a linha*/
  76.     while((c=getopt(argc,argv,":lwc"))!=-1)
  77.     switch(c)
  78.     {
  79.         case 'l': printf("%d\n",linhas(fp));
  80.             break;
  81.         case 'w': printf("%d\n",words(fp));
  82.             break;
  83.         case 'c': printf("%d\n",chars(fp));
  84.             break;
  85.         default: printf("not c l or w\nwill use -c as default:\n"); printf("%d\n",chars(fp)); break;
  86.     }
  87.     fclose(fp);
  88.     return 0;
  89. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement