47 lines
1 KiB
C
47 lines
1 KiB
C
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
#include <unistd.h>
|
|
#include <string.h>
|
|
#include <getopt.h>
|
|
#include <time.h>
|
|
|
|
int main(int argc, char *argv[]) {
|
|
int max_lines = -1; // -1 means unlimited
|
|
int verbose = 0;
|
|
|
|
// Parse arguments (-n max_lines, -v verbose)
|
|
char opt;
|
|
while ((opt = getopt(argc, argv, "n:v")) != -1) {
|
|
switch (opt) {
|
|
case 'n':
|
|
max_lines = atoi(optarg); break;
|
|
case 'v':
|
|
verbose = 1; break;
|
|
default:
|
|
printf("Usage: %s [-n max_lines] [-v]\n", argv[0]);
|
|
return 1;
|
|
}
|
|
}
|
|
|
|
// Read from stdin line by line
|
|
// Count lines and characters
|
|
// If verbose, echo lines to stdout
|
|
char buffer[256];
|
|
int lines = 0;
|
|
int chars = 0;
|
|
while (fgets(buffer, sizeof(buffer), stdin) != NULL) {
|
|
int size = strlen(buffer);
|
|
if (verbose)
|
|
fwrite(buffer, sizeof(char), size, stdout);
|
|
chars += size;
|
|
if (size > 0 && buffer[size - 1] == '\n')
|
|
lines++;
|
|
if (lines == max_lines)
|
|
break;
|
|
}
|
|
|
|
// Print statistics to stderr
|
|
fprintf(stderr, "Lines: %d\n", lines);
|
|
|
|
return 0;
|
|
}
|