wc/lc/lc.c

36 lines
731 B
C
Raw Normal View History

2023-09-10 13:05:28 +00:00
#include <stdio.h>
#include <unistd.h>
int lc(FILE* fp)
{
char c[1];
int num_lines = 0;
int fn = fileno(fp);
while (read(fn, c, sizeof(c)) > 0) {
if (*c == '\n' ) {
num_lines ++;
}
}
printf("%i\n", num_lines);
return 0;
}
int main(int argc, char** argv)
{
if (argc == 1) {
return lc(stdin);
} else if (argc > 1) {
FILE* fp = fopen(argv[1], "r");
if (!fp) {
perror("Could not open file");
return 1;
}
return lc(fp) && fclose(fp);
} else {
printf("Usage: lc file.txt\n");
printf(" or: cat file.txt | lc\n");
printf(" or: lc # read from user-inputted stdin\n");
}
return 0;
}