logo

utils-std

Collection of commonly available Unix tools git clone https://anongit.hacktivis.me/git/utils-std.git/
commit: 72675c301e1c6ceeece523be4206d6cc31588da2
parent 60f4d370a4ea9482b66176f1b2e8a7f5d504c7c6
Author: Haelwenn (lanodan) Monnier <contact@hacktivis.me>
Date:   Thu, 16 Jan 2025 19:15:46 +0100

cmd/shuf: switch from atoi to strtoul

Diffstat:

Mcmd/shuf.c37+++++++++++++++++++++++++++++--------
1 file changed, 29 insertions(+), 8 deletions(-)

diff --git a/cmd/shuf.c b/cmd/shuf.c @@ -7,7 +7,7 @@ #include <errno.h> #include <stdbool.h> #include <stdio.h> // getdelim, fprintf -#include <stdlib.h> // free, malloc, srand, rand, exit +#include <stdlib.h> // free, malloc, srand, rand, exit, strtoul #include <string.h> // strerror, memcpy #include <time.h> // time #include <unistd.h> // getopt @@ -26,8 +26,8 @@ static char delim = '\n'; char *line = NULL; size_t line_len = 0; -int wrote = 0; -int write_limit = 0; +unsigned long wrote = 0; +unsigned long write_limit = 0; static int shuf(FILE *in, const char *fname) @@ -92,15 +92,36 @@ main(int argc, char *argv[]) bool e_flag = false; srand((int)time(NULL)); - for(int c = -1; (c = getopt(argc, argv, ":enz")) != -1;) + for(int c = -1; (c = getopt(argc, argv, ":en:z")) != -1;) { + char *endptr = NULL; + switch(c) { case 'e': e_flag = true; break; case 'n': - write_limit = atoi(optarg); + write_limit = strtoul(optarg, &endptr, 0); + if(errno != 0) + { + fprintf(stderr, + "%s: error: Failed parsing number for `-n %s`: %s\n", + argv0, + optarg, + strerror(errno)); + return 1; + } + + if(endptr != NULL && *endptr != 0) + { + fprintf(stderr, + "%s: error: Found extraneous characters while parsing `-n %s` as a number: %s\n", + argv0, + optarg, + endptr); + return 1; + } break; case 'z': delim = '\0'; @@ -132,10 +153,10 @@ main(int argc, char *argv[]) argv[argc - 1] = tmp; } - int limit = argc; - if(write_limit != 0 && write_limit < argc) limit = write_limit; + unsigned long limit = argc; + if(write_limit != 0 && write_limit < limit) limit = write_limit; - for(int i = 0; i < limit; i++) + for(unsigned long i = 0; i < limit; i++) { printf("%s%c", argv[i], delim); }