[tpwd] Fix segfault when exactly one argument given
[tinyapps.git] / errno
blob5efb9db26fb5f4a310745fd94770022883c68e74
1 #!/usr/bin/perl
2 ##
3 ## Prints out error message according to name or number
4 ## Copyright (c) 2010 by Michal Nazarewicz (mina86/AT/mina86.com)
5 ##
6 ## This program is free software; you can redistribute it and/or modify
7 ## it under the terms of the GNU General Public License as published by
8 ## the Free Software Foundation; either version 3 of the License, or
9 ## (at your option) any later version.
11 ## This program is distributed in the hope that it will be useful,
12 ## but WITHOUT ANY WARRANTY; without even the implied warranty of
13 ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 ## GNU General Public License for more details.
16 ## You should have received a copy of the GNU General Public License
17 ## along with this program; if not, see <http://www.gnu.org/licenses/>.
19 ## This is part of Tiny Applications Collection
20 ## -> http://tinyapps.sourceforge.net/
23 use warnings;
24 use strict;
26 use POSIX qw(strerror);
27 use FileHandle;
28 use IPC::Open2;
31 unless (@ARGV) {
32 print "usage: errno <error> [ ... ]\n where <error> is either an errno number or EFOO symbol.\n Requires gcc to work.\n";
33 exit 0;
37 my (%names, %nums);
39 open2(*IN, *OUT, "gcc -E -dM -") or die "gcc: $!\n";
41 print OUT "#include <errno.h>\n";
42 close OUT;
44 while (<IN>) {
45 if (/^#define\s+(E[A-Z0-9]+)\s+(\d+)\s*$/) {
46 my $n = int $2;
47 $nums{$1} = $n;
48 $names{$n} = $1 unless exists $names{$n};
51 close IN;
54 for (@ARGV) {
55 my ($name, $num, $err);
57 if (/^-?\d+$/) {
58 $num = abs $_;
59 $name = $names{$num} // 'unknown';
60 } elsif (/^E[A-Z0-9]+$/i) {
61 $name = uc $_;
62 $num = $nums{$name};
63 if (!defined $num) {
64 print STDERR "$name: no such error\n";
65 next;
67 } else {
68 print STDERR "$_: ignoring\n";
69 next;
72 $err = strerror($num);
73 if ($err) {
74 print "$num: $name: $err\n";
75 } else {
76 print STDERR "$num: $name: no such error\n";