(以下内容来自《The C Programming Language》)
输入和输出是由read和write两个系统调用实现的。在C语言程序中,可以通过函数read和write访问这两个系统调用。
这两个函数原型为:
int n_read = read(int fd,char *buf,int n);
int n_written = write(int fd,char *buf,int n);
这两个函数的第一个参数都是文件描述符,第二个参数是程序中存放读或者写的数据的字符数组,第三个参数是要传输的字节数。每个调用返回实际传输的字节数。返回0则表示已经到达文件末尾;返回-1则表示发生了某种错误。写文件时,返回实际写入的字节数。
1.使用read和write将输入赋值到输出
下面是一个简单的例子,实现将任意输入复制到任意输出。
#include "sys/syscall.h"//定义read和write函数的头文件
#include <stdio.h> //定义BUFSIZ的头文件
int main()
{
char buf[BUFSIZ];
int n;
while((n=read(0,buf,BUFSIZ))>0)
write(1,buf,n);
return 0;
}
2.getchar()版本1
getchar函数每次从标准输入读入一个字符。
#include "sys/syscall.h"
#include <stdio.h>
int getchar(void)
{
char c;
return (read(0,&c,1)==1)?(unsigned char)c:EOF
//EOF定义在stdio.h文件中
}
3.getchar()版本2
这个getchar()每次读入一组字符,但每次只输出一个字符。
#include "sys/syscall.h"
#include<stdio.h>
int gchar(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;
}