天天看點

C 中 getline (類似fgets) 的實作方法

long getline(int fd, char *buf, long len)

{

long cur = lseek(fd, 0, SEEK_CUR);

long ret = read(fd, buf, len);

int index = 0;

if(ret <= 0) {

return ret;

}

while(buf[index++] != '\n' && index < ret);

if(index < ret) {

lseek(fd, cur + index, SEEK_SET);

}

if(index < len) {

buf[index] = 0;

}

return index; 

}