k9core/src/wc.c

73 lines
1.3 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-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;
// printf("%i %i %i\n",newlines,spaces,bytes);
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-28 12:26:08 +00:00
int c = getopt(argc, argv, "clw");
struct wc_values data;
2020-06-16 19:28:56 +00:00
if (argc == 1)
2020-07-28 12:26:08 +00:00
data = wc(stdin);
2020-06-16 19:28:56 +00:00
else
{
2020-07-28 12:26:08 +00:00
for(int i = optind; i<argc;i++)
{
data = wc(fopen(argv[i],"r"));
switch(c)
{
case 'c':
printf("%i\n",data.bytes);
break;
case 'l':
printf("%i\n",data.lines);
break;
case 'w':
printf("%i\n",data.words);
break;
default:
printf("%i %i %i\n",data.lines,data.words,data.bytes);
}
}
2020-06-16 19:28:56 +00:00
}
2020-06-16 16:52:17 +00:00
return 0;
}