| 709 | BUF contains the first INITIAL_READ input bytes. */ |
| 710 | |
| 711 | static void |
| 712 | bytes_split (intmax_t n_bytes, intmax_t rem_bytes, |
| 713 | char *buf, idx_t bufsize, ssize_t initial_read, |
| 714 | intmax_t max_files) |
| 715 | { |
| 716 | bool new_file_flag = true; |
| 717 | bool filter_ok = true; |
| 718 | intmax_t opened = 0; |
| 719 | intmax_t to_write = n_bytes + (0 < rem_bytes); |
| 720 | bool eof = ! to_write; |
| 721 | |
| 722 | while (! eof) |
| 723 | { |
| 724 | ssize_t n_read; |
| 725 | if (0 <= initial_read) |
| 726 | { |
| 727 | n_read = initial_read; |
| 728 | initial_read = -1; |
| 729 | eof = n_read < bufsize; |
| 730 | } |
| 731 | else |
| 732 | { |
| 733 | if (! filter_ok |
| 734 | && 0 <= lseek (STDIN_FILENO, to_write, SEEK_CUR)) |
| 735 | { |
| 736 | to_write = n_bytes + (opened + 1 < rem_bytes); |
| 737 | new_file_flag = true; |
| 738 | } |
| 739 | |
| 740 | n_read = read (STDIN_FILENO, buf, bufsize); |
| 741 | if (n_read < 0) |
| 742 | error (EXIT_FAILURE, errno, "%s", quotef (infile)); |
| 743 | eof = n_read == 0; |
| 744 | } |
| 745 | char *bp_out = buf; |
| 746 | while (0 < to_write && to_write <= n_read) |
| 747 | { |
| 748 | if (filter_ok || new_file_flag) |
| 749 | filter_ok = cwrite (new_file_flag, bp_out, to_write); |
| 750 | opened += new_file_flag; |
| 751 | new_file_flag = !max_files || (opened < max_files); |
| 752 | if (! filter_ok && ! new_file_flag) |
| 753 | { |
| 754 | /* If filters no longer accepting input, stop reading. */ |
| 755 | n_read = 0; |
| 756 | eof = true; |
| 757 | break; |
| 758 | } |
| 759 | bp_out += to_write; |
| 760 | n_read -= to_write; |
| 761 | to_write = n_bytes + (opened < rem_bytes); |
| 762 | } |
| 763 | if (0 < n_read) |
| 764 | { |
| 765 | if (filter_ok || new_file_flag) |
| 766 | filter_ok = cwrite (new_file_flag, bp_out, n_read); |
| 767 | opened += new_file_flag; |
| 768 | new_file_flag = false; |