Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <unistd.h>
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #define exit_on_null(s,m) if(s == NULL) { perror(m); exit(1); }
- int linhas(FILE *f)
- {
- char *line = NULL;
- ssize_t n=0;
- int l=0;
- while((n = getline(&line, &n, f)) != -1)
- {
- l++;
- }
- if(line) free(line);
- return l;
- }
- int words(FILE *f)
- {
- char *line = NULL;
- ssize_t n=0;
- int w=0, i;
- char flag=0;
- while((n = getline(&line, &n, f)) != -1)
- {
- i=0;
- while(line[i] != '\0')
- {
- if(line[i] == ' ' && flag)
- {
- w++;
- flag=0;
- }
- else if(line[i] != ' ' && !flag)
- flag = 1;
- i++;
- }
- if(flag)
- {
- w++;
- flag = 0;
- }
- }
- if(line) free(line);
- return w;
- }
- int chars(FILE *f)
- {
- char *line = NULL;
- ssize_t n=0;
- int c=0;
- while((n = getline(&line, &n, fp)) != -1)
- count+=strlen(line)-1;
- if(line) free(line);
- return c;
- }
- int main (int argc, char *argv[])
- {
- FILE *fp;
- int c;
- /* Usage */
- if (argc<=2)
- {
- printf("Usage: %s <file name>\n",argv[0]);
- exit(1);
- }
- fp=fopen(argv[1],"r");/*Abre ficheiro para leitura*/
- exit_on_null(fp,"Erro na abertura");
- /*Leitura linha a linha*/
- while((c=getopt(argc,argv,":lwc"))!=-1)
- switch(c)
- {
- case 'l': printf("%d\n",linhas(fp));
- break;
- case 'w': printf("%d\n",words(fp));
- break;
- case 'c': printf("%d\n",chars(fp));
- break;
- default: printf("not c l or w\nwill use -c as default:\n"); printf("%d\n",chars(fp)); break;
- }
- fclose(fp);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement