您的位置:首页 > 其它

FILE *stdout 和 STDOUT_FILENO 的区别

2017-06-01 14:40 701 查看
转自:http://blog.sina.com.cn/s/blog_9f1496990100y3st.html

首先要知道 FILE *stdout 和 STDOUT_FILENO 的区别。

stdin类型为 FILE*

STDIN_FILENO类型为 int

使用stdin的函数主要有:fread、fwrite、fclose等,基本上都以f开头

使用STDIN_FILENO的函数有:read、write、close等

操作系统一级提供的文件API都是以文件描述符来表示文件。STDIN_FILENO就是标准输入设备(一般是键盘)的文件描述符。

标准C++一级提供的文件操作函数库都是用FILE*来表示文件,stdin就是指向标准输入设备文件的FILE*。

如下:

参考stdin(3)的man手册:
Name
stdin, stdout, stderr - standard I/O streams
Synopsis
#include <stdio.h>
extern FILE *stdin;
extern FILE *stdout;
extern FILE *stderr;
...
On program startup, the integer file descriptors associated with the streams stdin, stdout, and stderr are 0, 1, and 2, respectively. The preprocessor symbols STDIN_FILENO, STDOUT_FILENO, and STDERR_FILENO are defined with these values in <unistd.h>. (Applying freopen(3) to one of these streams can change the file descriptor number associated with the stream.)
...


stdin / stdout / stderr

分别是指向stream的FILE型的指针变量。

当程序启动时,与其结合的整型文件描述符(fd)分别是0,1,2。

STDIN_FILENO / STDOUT_FILENO / STDERR_FILENO

是在

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

#define CHANGE_BY_FREOPEN

int main(int argc,char**argv){
char buf[]="hello,world\n";

#ifdef CHANGE_BY_FREOPEN
freopen("stdout_text.txt","w",stdout);
//freopen("stderr_text.txt","w",stderr);
#endif

printf("%s",buf);
fwrite(buf,strlen(buf), 1,stdout);
write(STDOUT_FILENO,&buf,strlen(buf));
perror("error out");

return(0);
}


编译命令,生成可执行文件 stdouttest

$ gcc -o stdouttest stdouttest.c




当 #define CHANGE_BY_FREOPEN 被注释掉,无效的时候:

终端shell窗口中的输出结果是:

$ ./stdouttest
hello,world
hello,world
hello,world
error out: No error
$


注:

3个(hello,world + 换行符)。

1个error的输出

标准输入输出,都还是shell窗口。



当 #define CHANGE_BY_FREOPEN ,有效的时候:

终端shell窗口中的输出结果是:

$ ./stdouttest
error out: No error
$


注:shell窗口中,仅有stderr的输出。

但是,会创建一个名为stdout_text.txt的文件,

该文件中的内容是:

hello,world

hello,world

hello,world

注:

3个(hello,world + 换行符)。

仅标准输出,从shell窗口,改变为stdout_text.txt的文件了。

//freopen(“stderr_text.txt”,”w”,stderr);

如果有效的话:

①shell中,什么也不输出。

②stdout_text.txt 中,输出3个(hello,world + 换行符)。

③stderr_text.txt 中,输出1个(error out: No error)。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: