k9core/src/wc.c

92 lines
1.6 KiB
C
Raw Normal View History

2020-06-16 16:52:17 +00:00
#include <stdio.h>
2020-07-28 10:46:55 +00:00
#include <ctype.h>
2020-07-28 12:26:08 +00:00
#include <getopt.h>
#include <stdlib.h>
2020-06-16 16:52:17 +00:00
2020-07-29 20:49:00 +00:00
/* TODO: fix stdin */
2020-07-28 12:26:08 +00:00
struct wc_values
{
int lines;
int bytes;
int words;
};
struct wc_values
2020-06-16 19:28:56 +00:00
wc(FILE *file)
2020-06-16 16:52:17 +00:00
{
2020-07-28 12:26:08 +00:00
if(file == NULL)
{
fprintf(stderr,"error\n");
exit(1);
}
struct wc_values foobar;
2020-06-16 16:52:17 +00:00
char c;
2020-06-16 19:28:56 +00:00
int newlines, spaces, bytes = 0;
newlines = spaces = bytes = 0;
while((c = fgetc(file)) > 0)
2020-06-16 16:52:17 +00:00
{
bytes++;
if(c == '\n')
newlines++;
2020-07-28 10:46:55 +00:00
if(isspace(c))
2020-06-16 16:52:17 +00:00
spaces++;
}
2020-07-28 12:26:08 +00:00
foobar.bytes = bytes;
foobar.lines = newlines;
foobar.words = spaces;
2020-06-16 19:28:56 +00:00
fclose(file);
2020-07-28 12:26:08 +00:00
return foobar;
2020-06-16 19:28:56 +00:00
}
int
main(int argc, char *argv[])
{
2020-07-29 20:49:00 +00:00
int c;
int show_lines, show_words, show_bytes;
show_lines = show_words = show_bytes = 1;
2020-07-28 12:26:08 +00:00
struct wc_values data;
2020-07-29 20:49:00 +00:00
/* Process arguments */
while((c = getopt(argc,argv,"lwc")) > 0)
{
switch(c)
2020-07-30 11:59:34 +00:00
{
case 'l':
show_lines = 0;
2020-07-30 11:59:34 +00:00
break;
case 'w':
show_words = 0;
2020-07-30 11:59:34 +00:00
break;
case 'c':
show_bytes = 0;
2020-07-30 11:59:34 +00:00
break;
}
2020-07-29 20:49:00 +00:00
}
for(int i = optind; i<argc;i++)
2020-06-16 19:28:56 +00:00
{
2020-07-29 20:49:00 +00:00
if(argc > 1)
2020-07-30 11:59:34 +00:00
{
if(argc > i)
data = wc(fopen(argv[i],"r"));
else
data = wc(stdin);
if(show_lines && show_words && show_bytes)
printf("%i %i %i",data.lines, data.words, data.bytes);
else
{
if(!show_lines)
printf("%i ",data.lines);
if(!show_words)
printf("%i ",data.words);
if(!show_bytes)
printf("%i ",data.bytes);
}
2020-07-30 11:59:34 +00:00
}
printf("\n");
2020-06-16 19:28:56 +00:00
}
2020-07-30 11:59:34 +00:00
2020-06-16 16:52:17 +00:00
return 0;
}