Skip to content

Commit

Permalink
proper stdio error handling
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
nabijaczleweli committed Jul 5, 2024
1 parent b372f73 commit 06ae0d8
Showing 1 changed file with 13 additions and 6 deletions.
19 changes: 13 additions & 6 deletions xclip.c
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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)
*/
Expand All @@ -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,
Expand Down

0 comments on commit 06ae0d8

Please sign in to comment.