I was trying to implement getchar() function using read() in unistd.h.
Since system calls are pricy, I wanted to execute less read() functions as possible.
If I use "getchar", it works fine. However, "mygetchar" does not work in this case.
Can anyone point out what I have done wrong below?
#include <stdio.h>
#include <unistd.h>
#define BUF_SIZE 1024
int startIndex;
int endIndex;
int mygetchar(void){
char buffer[BUF_SIZE];
startIndex=0;
endIndex=0;
if(startIndex == endIndex){
int r;
r = read(0,buffer,BUF_SIZE);
startIndex=0;
endIndex=r;
}
return buffer[startIndex++];
}
int main(){
char c;
int i=0;
do{
c = mygetchar();
putchar(c);
i++;
}
while(c != EOF);
return 0;
}