0 标准输入
1 标准输出
2 标准错误
int n_read = read(int fd, char *buf, int n);
int n_write = write(int fd, char *buf, int n);
#include "stdio.h"
#include "unistd.h"
#define BUF 6
void copy01();
int getchar01();
int getchar02();
int main()
{
copy01();
char c;
c = getchar01();
printf("%c\n", c);
c = getchar01(); // 等待read
printf("%c\n", c);
c = getchar02();
printf("%c\n", c);
c = getchar02();
c = getchar02();
c = getchar02(); // 要么从缓存里面取,要么等待read
c = getchar02();
c = getchar02();
c = getchar02();
printf("%c\n", c);
// 注明: 如果把getchar02放到01前面执行,02会一次性尽量读取BUFSIZE512个字符,
// 会发现01要等待第二次的标准输入。
return 0;
}
/* 复制标准输入到标准输出 */
void copy01(void)
{
char exit0 = '0';
char buf[BUF];
int n;
printf("请输入内容,回车结束。输入0时,退出复制。\n");
while ((n = read(0, buf, BUF)) > 0)
{
if (buf[0] == exit0)
{
printf("退出。\n");
break;
}
write(1, buf, n);
}
}
/* 不带缓冲的getchar */
int getchar01(void)
{
char c;
return (read(0, &c, 1) == 1) ? (unsigned char)c : EOF;
}
/* 带缓冲的getchar */
int getchar02(void)
{
static char buf[BUFSIZ];
static char *bufp = buf;
static int n = 0;
if (n == 0)
{
n = read(0, buf, sizeof(buf));
bufp = buf;
}
return (--n >= 0) ? (unsigned char)*bufp++ : EOF;
}