unsigned long nextInt()

in commons-rng-examples/examples-stress/src/main/c/stdin2testu01.c [141:173]


unsigned long nextInt(void *par,
                      void *sta) {
  static size_t last_read = 0;

  StdinReader_state *state = (StdinReader_state *) sta;
  if (state->index >= last_read) {
    /* Refill. */
    last_read = fread(state->buffer, sizeof(uint32_t), BUFFER_LENGTH_32, stdin);
    if (last_read != BUFFER_LENGTH_32) {
      // Allow reading less than the buffer length, but not zero
      if (last_read == 0) {
        // Error handling
        if (feof(stdin)) {
          // End of stream, just exit. This is used for testing.
          exit(0);
        } else if (ferror(stdin)) {
          // perror will contain a description of the error code
          perror("[ERROR] Failed to read stdin");
          exit(1);
        } else {
          printf("[ERROR] No data from stdin\n");
          exit(1);
        }
      }
    }
    state->index = 0;
  }

  uint32_t random = state->buffer[state->index];
  ++state->index; /* Next request. */

  return random;
}