Friday, December 5, 2014

Read4096 - Google Interview Question

Google Interview Question Software Engineer

Given API:
int Read4096(char* buf);
It reads data from a file and records the position so that the next time when it is called it read the next 4k chars (or the rest of the file, whichever is smaller) from the file.
The return is the number of chars read.

Todo: Use above API to Implement API
"int Read(char* buf, int n)" which reads any number of chars from the file.


Answer:

int read(char* buf, int n){
  int num_it = n / 4096;
  int remain = n % 4096;
  int total = 0;

  while(num_it--){
    int num_read = read4096(buf);
    if(num_read == 0) break;
    buf += num_read;
    total += num_read;
  }

  if(total != n-remain) return total;

  char readbuf[4096];
  int num_read = read4096(readbuf);
  int num_copy = min(num_read, remain);
  copy(readbuf, readbuf + num_copy, buf);
  total += num_copy;

  return total;
}

No comments:

Post a Comment