| 1065 | /* -n K/N: Extract Kth of N chunks. */ |
| 1066 | |
| 1067 | static void |
| 1068 | bytes_chunk_extract (intmax_t k, intmax_t n, char *buf, idx_t bufsize, |
| 1069 | ssize_t initial_read, off_t file_size) |
| 1070 | { |
| 1071 | off_t start; |
| 1072 | off_t end; |
| 1073 | |
| 1074 | affirm (0 < k && k <= n); |
| 1075 | |
| 1076 | start = (k - 1) * (file_size / n) + MIN (k - 1, file_size % n); |
| 1077 | end = k == n ? file_size : k * (file_size / n) + MIN (k, file_size % n); |
| 1078 | |
| 1079 | if (start < initial_read) |
| 1080 | { |
| 1081 | memmove (buf, buf + start, initial_read - start); |
| 1082 | initial_read -= start; |
| 1083 | } |
| 1084 | else |
| 1085 | { |
| 1086 | if (initial_read < start |
| 1087 | && lseek (STDIN_FILENO, start - initial_read, SEEK_CUR) < 0) |
| 1088 | error (EXIT_FAILURE, errno, "%s", quotef (infile)); |
| 1089 | initial_read = -1; |
| 1090 | } |
| 1091 | |
| 1092 | while (start < end) |
| 1093 | { |
| 1094 | ssize_t n_read; |
| 1095 | if (0 <= initial_read) |
| 1096 | { |
| 1097 | n_read = initial_read; |
| 1098 | initial_read = -1; |
| 1099 | } |
| 1100 | else |
| 1101 | { |
| 1102 | n_read = read (STDIN_FILENO, buf, bufsize); |
| 1103 | if (n_read < 0) |
| 1104 | error (EXIT_FAILURE, errno, "%s", quotef (infile)); |
| 1105 | } |
| 1106 | if (n_read == 0) |
| 1107 | break; /* eof. */ |
| 1108 | n_read = MIN (n_read, end - start); |
| 1109 | if (full_write (STDOUT_FILENO, buf, n_read) != n_read |
| 1110 | && ! ignorable (errno)) |
| 1111 | error (EXIT_FAILURE, errno, "%s", quotef ("-")); |
| 1112 | start += n_read; |
| 1113 | } |
| 1114 | } |
| 1115 | |
| 1116 | typedef struct of_info |
| 1117 | { |