From 06ae0d898e13f39d3a7da3dd6ea09cc6a6ee5dda Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=BD=D0=B0=D0=B1?= Date: Fri, 5 Jul 2024 15:49:51 +0200 Subject: [PATCH] proper stdio error handling Correctly detect errors from stdio: $ ./xclip < . ./xclip: (stdin): Is a directory $ ./xclip . ./xclip: .: Is a directory $ xclip . ^C also, by reordering the loop and the condition this way, we only allocate more if we know there's more, and only check for EOF if we encountered an EOF or error. --- xclip.c | 19 +++++++++++++------ 1 file changed, 13 insertions(+), 6 deletions(-) diff --git a/xclip.c b/xclip.c index dc9b395..3d6634a 100644 --- a/xclip.c +++ b/xclip.c @@ -378,8 +378,9 @@ doIn(Window win, const char *progname) } else { if ((fil_handle = fopen(fil_names[fil_current], "r")) == NULL) { - errperror(3, progname, ": ", fil_names[fil_current] - ); + err: + errperror(3, progname, ": ", + fil_number ? fil_names[fil_current] : "(stdin)"); return EXIT_FAILURE; } else { @@ -390,8 +391,15 @@ doIn(Window win, const char *progname) } } - fil_current++; - while (!feof(fil_handle)) { + for (;;) { + size_t rd = fread(sel_buf + sel_len, sizeof(char), sel_all - sel_len, fil_handle); + if (rd != sel_all - sel_len) { + if (feof(fil_handle)) + break; + goto err; + } + sel_len += rd; + /* If sel_buf is full (used elems = * allocated elems) */ @@ -405,14 +413,13 @@ doIn(Window win, const char *progname) fprintf(stderr, "xclip: debug: Increased buffersize to %ld\n", sel_all); } } - sel_len += fread(sel_buf + sel_len, sizeof(char), sel_all - sel_len, fil_handle); } if (fil_handle && (fil_handle != stdin)) { fclose(fil_handle); fil_handle = NULL; } - } while (fil_current < fil_number); + } while (++fil_current < fil_number); /* if there are no files being read from (i.e., input * is from stdin not files, and we are in filter mode,