networking · beginner · ~15 min

Reads needed for a response

Estimate the recv-loop iteration count.

Challenge

A client reading at most chunk bytes per recv needs several calls to read a whole response. Compute how many recv calls are required.

Task

Implement int reads_needed(int total, int chunk) that returns the number of recv calls (a ceiling division of total by chunk). Return 0 if chunk <= 0.

Input

  • total: total bytes to read.
  • chunk: maximum bytes read per call.

Output

Returns ceil(total / chunk), or 0 when chunk <= 0.

Example

reads_needed(1000, 256)   ->   4
reads_needed(512, 256)    ->   2
reads_needed(100, 0)      ->   0

Edge cases

  • chunk <= 0: return 0 (avoid dividing by zero).

Input format

Two integers: total bytes and chunk size per read.

Output format

ceil(total / chunk), or 0 if chunk <= 0.

Constraints

Use ceiling division; guard chunk <= 0 by returning 0.

Starter code

int reads_needed(int total, int chunk) {
    /* TODO */
    return 0;
}

Common mistakes

Assuming read/write transmits all requested bytes at once; ignoring socket file descriptor cleanup; unhandled endianness conversions.

Edge cases to handle

Short reads/writes; peer closing socket (recv returns 0); signal interruption (EINTR); non-blocking EAGAIN.

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.