logo

utils-std

Collection of commonly available Unix tools git clone https://anongit.hacktivis.me/git/utils-std.git/
commit: 420476103f931781b38ec029f12ff8356cce30a4
parent ec541835b6b148f11fe2d693ceea6e048ac512b9
Author: Haelwenn (lanodan) Monnier <contact@hacktivis.me>
Date:   Mon, 16 Dec 2024 22:39:56 +0100

cmd/uniq: close opened files before returning

Diffstat:

Mcmd/uniq.c40++++++++++++++++++++++++++++++++++++++--
1 file changed, 38 insertions(+), 2 deletions(-)

diff --git a/cmd/uniq.c b/cmd/uniq.c @@ -114,7 +114,9 @@ main(int argc, char *argv[]) assert(errno == 0); FILE *input = stdin; + char *input_name = NULL; FILE *output = stdout; + char *output_name = NULL; switch(argc) { @@ -122,6 +124,7 @@ main(int argc, char *argv[]) break; case 1: input = fopen(argv[0], "r"); + input_name = argv[0]; if(input == NULL) { fprintf( @@ -131,6 +134,7 @@ main(int argc, char *argv[]) break; case 2: input = fopen(argv[0], "r"); + input_name = argv[0]; if(input == NULL) { fprintf( @@ -138,10 +142,18 @@ main(int argc, char *argv[]) return 1; } output = fopen(argv[1], "w"); + output_name = argv[1]; if(output == NULL) { fprintf( stderr, "uniq: error: Failed opening output file '%s': %s\n", argv[1], strerror(errno)); + + if(fclose(input) != 0) + fprintf(stderr, + "uniq: error: Failed closing input file '%s': %s\n", + input_name, + strerror(errno)); + return 1; } break; @@ -252,11 +264,35 @@ main(int argc, char *argv[]) } } + int ret = 0; + if(errno != 0) { fprintf(stderr, "uniq: error: Failed reading: %s\n", strerror(errno)); - return 1; + ret = 1; + } + + if(input != stdin) + { + if(fclose(input) != 0) + { + fprintf( + stderr, "uniq: error: Failed closing input file '%s': %s\n", input_name, strerror(errno)); + ret = 1; + } + } + + if(output != stdout) + { + if(fclose(output) != 0) + { + fprintf(stderr, + "uniq: error: Failed closing output file '%s': %s\n", + output_name, + strerror(errno)); + ret = 1; + } } - return 0; + return ret; }