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;
}