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"
|
|
|
|
|
2024-03-16 08:02:43 +00:00
|
|
|
int w_flag = 4;
|
|
|
|
int lines = 1;
|
2023-12-01 21:09:37 +00:00
|
|
|
|
|
|
|
int nl(const char *path) {
|
|
|
|
FILE *fp = stdin;
|
|
|
|
|
|
|
|
if (strcmp(path, "-"))
|
|
|
|
fp = fopen(path, "r");
|
|
|
|
|
|
|
|
if (fp == NULL) {
|
2023-12-17 08:23:09 +00:00
|
|
|
fprintf(stderr, "nl: %s: %s\n", path, strerror(errno));
|
2023-12-01 21:09:37 +00:00
|
|
|
return 1;
|
|
|
|
}
|
|
|
|
|
2023-12-17 13:45:13 +00:00
|
|
|
char *buf = NULL;
|
|
|
|
size_t size = 0;
|
|
|
|
while (getline(&buf, &size, fp) != EOF) {
|
|
|
|
if (strlen(buf) > 1)
|
2024-03-27 19:04:17 +00:00
|
|
|
fprintf(stdout, "%*d\t%s", w_flag, lines++, buf);
|
2023-12-01 21:09:37 +00:00
|
|
|
|
2023-12-02 12:48:28 +00:00
|
|
|
else
|
|
|
|
fprintf(stdout, "%*s\t%s", w_flag, " ", buf);
|
|
|
|
}
|
|
|
|
|
2023-12-25 16:10:44 +00:00
|
|
|
if (buf != NULL)
|
|
|
|
free(buf);
|
2023-12-17 13:45:13 +00:00
|
|
|
|
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:
|
2024-03-03 13:34:11 +00:00
|
|
|
printf("nl [wv] [file1 file2...]\n\t-w N Width of line numbers\n\t-v N Start from N\n");
|
2023-12-01 21:09:37 +00:00
|
|
|
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;
|
|
|
|
}
|
|
|
|
}
|