2023-12-01 21:09:37 +00:00
|
|
|
#include <fcntl.h>
|
|
|
|
#include <stdio.h>
|
|
|
|
#include <errno.h>
|
2023-12-02 12:48:28 +00:00
|
|
|
#include <stdlib.h>
|
2023-12-01 21:09:37 +00:00
|
|
|
#include <string.h>
|
|
|
|
#include <unistd.h>
|
|
|
|
#include "config.h"
|
|
|
|
|
2023-12-02 12:48:28 +00:00
|
|
|
unsigned int w_flag = 4;
|
2023-12-01 21:09:37 +00:00
|
|
|
unsigned int lines = 1;
|
|
|
|
|
|
|
|
int nl(const char *path) {
|
|
|
|
FILE *fp = stdin;
|
|
|
|
|
|
|
|
if (strcmp(path, "-"))
|
|
|
|
fp = fopen(path, "r");
|
|
|
|
|
|
|
|
if (fp == NULL) {
|
|
|
|
fprintf(stderr, "rev: %s: %s\n", path, strerror(errno));
|
|
|
|
return 1;
|
|
|
|
}
|
|
|
|
|
|
|
|
char buf[BUF_SIZE + 1];
|
2023-12-02 12:48:28 +00:00
|
|
|
while (fgets(buf, sizeof(buf), fp)) {
|
2023-12-01 21:09:37 +00:00
|
|
|
if (strlen(buf) > 1)
|
|
|
|
fprintf(stdout, "%*u\t%s", w_flag, lines++, buf);
|
|
|
|
|
2023-12-02 12:48:28 +00:00
|
|
|
else
|
|
|
|
fprintf(stdout, "%*s\t%s", w_flag, " ", buf);
|
|
|
|
}
|
|
|
|
|
2023-12-01 21:09:37 +00:00
|
|
|
if (strcmp(path, "-"))
|
|
|
|
fclose(fp);
|
|
|
|
|
|
|
|
return 0;
|
|
|
|
}
|
|
|
|
|
|
|
|
int main(int argc, char **argv) {
|
|
|
|
int opt;
|
|
|
|
while ((opt = getopt(argc, argv, "w:v:")) != -1) {
|
|
|
|
switch (opt) {
|
|
|
|
case 'w':
|
|
|
|
w_flag = atoi(optarg);
|
|
|
|
break;
|
|
|
|
|
|
|
|
case 'v':
|
|
|
|
lines = atoi(optarg);
|
|
|
|
break;
|
|
|
|
|
|
|
|
default:
|
|
|
|
printf("nl [file1 file2...]\n\t[-w N Width of line numbers]\n\t[-v N Start from N]\n");
|
|
|
|
return 0;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
argv += optind;
|
|
|
|
argc -= optind;
|
|
|
|
|
|
|
|
if (argc == 0)
|
|
|
|
return nl("-");
|
|
|
|
|
|
|
|
else {
|
|
|
|
int ret = 0;
|
|
|
|
for (int i = 0; i < argc; i++)
|
|
|
|
if (nl(argv[i]))
|
|
|
|
ret = 1;
|
|
|
|
|
|
|
|
return ret;
|
|
|
|
}
|
|
|
|
}
|