stdin,stdout 和 STDOUT_FILENO,STDIN_FILENO

stdin,stdout 等类型为 FILE *
STDIN_FILENO,STDOUT_FILENO,STDERR_FILENO 等类型为 int
使用 FILE * 的函数主要有:fopen、fread、fwrite、fclose等,基本上都以 f 开头。
使用 STDIN_FILENO 等的函数有:open、read、write、close等。

stdin 等属于标准 I/O,高级的输入输出函数,定义在 <stdio.h>
STDIN_FILENO 等是文件描述符,是非负整数,一般定义为0, 1, 2,直接调用系统调用,定义在 <unistd.h>

fileno() 函数可以用来取得 stream 指定的文件流所使用的文件描述符:

#include <stdio.h>
#include <unistd.h>


int main()
{
    printf("%d \n",fileno(stdin));		//0
    printf("%d \n",fileno(stdout));		//1
    printf("%d \n",fileno(stderr));		//2

    return 0;
}

接受标准输入,输出到标准输出:

#include <stdio.h>
#include <unistd.h>

#define SIZE 100

int main()
{
   int n;
   char buf[SIZE];

   while(n = read(STDIN_FILENO,buf,SIZE))
   {
       if(n != write(STDOUT_FILENO,buf,n))
            perror("write error");
   }

   if(n < 0)
        perror("read error");

   return 0;
}
posted @ 2019-11-11 12:17  youngliu91  阅读(2160)  评论(0编辑  收藏  举报