Skip to content

Commit

Permalink
fmt: indicate open() failure (#487)
Browse files Browse the repository at this point in the history
* Explicitly open() input files so we can exit with a failure code if open() fails
* Input loop is converted into a function; line buffer remains global
* Ignore directories as done by GNU fmt
* Read stdin if no file arguments are given
* Tested patch against previous version and I get the same output
  • Loading branch information
mknos committed Mar 9, 2024
1 parent 87d2885 commit aa62cea
Showing 1 changed file with 39 additions and 18 deletions.
57 changes: 39 additions & 18 deletions bin/fmt
Expand Up @@ -42,35 +42,56 @@ format =
.
FORMAT

while (<>) {
chomp;
if (length) {
if (length $line) {
my $last_char = substr $line, -1, 1;
if ('.' eq $last_char) {
$line .= " ";
} elsif (' ' ne $last_char and "\t" ne $last_char) {
$line .= " ";
}
}
$line .= $_;
} else {
do write while length $line;
print "\n";
my $rc = EX_SUCCESS;
foreach my $file (@ARGV) {
next if (-d $file);
my $fh;
unless (open $fh, '<', $file) {
warn "$Program: failed to open '$file': $!\n";
$rc = EX_FAILURE;
next;
}
fmt_file($fh);
unless (close $fh) {
warn "$Program: failed to close '$file': $!\n";
$rc = EX_FAILURE;
}
}

unless (@ARGV) {
fmt_file(*STDIN);
}
if (length $line) {
do write while length $line;
}

exit EX_SUCCESS;
exit $rc;

sub usage {
warn "usage: $Program [-w WIDTH] [file...]\n";
exit EX_FAILURE;
}

sub fmt_file {
my $fh = shift;

while (<$fh>) {
chomp;
if (length) {
if (length $line) {
my $last_char = substr $line, -1, 1;
if ('.' eq $last_char) {
$line .= " ";
} elsif (' ' ne $last_char and "\t" ne $last_char) {
$line .= " ";
}
}
$line .= $_;
} else {
do write while length $line;
print "\n";
}
}
}

# Take care of special case, bare -width option
sub new_argv {
my @new;
Expand Down

0 comments on commit aa62cea

Please sign in to comment.