文章目录
readLine函数
readLine()函数从文件描述符参数fd引用的文件中读取字节直到碰到换行符为止。函数成功时返回读取的字节数(结尾null字节不会计算在内)
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
ssize_t
readLine(int fd, void *buffer, size_t n)
{
ssize_t numRead;
size_t totRead;
char *buf;
char ch;
if (n <= 0 || buffer == NULL) {
errno = EINVAL;
return -1;
}
buf = buffer;
totRead = 0;
for (;;) {
numRead = read(fd, &ch, 1);
if (-1 == numRead) {
if (errno == EINTR) {
continue;
} else {
return -1;
}
} else if (numRead == 0) {
if (totRead == 0) {
return 0;
} else {
break;
}
} else {
if (totRead < n - 1) {
totRead++;
*buf++ = ch;
}
if (ch == '\n') {
break;
}
}
}
*buf = '\0';
return totRead;
}