源头:进程并不是从文件读取数据,而是从文件描述符读取数据。
将stdin定向到文件的方法
1.close the open
初始状态:系统中采用的是典型的设置---三种标准流被连接到终端设备上:输入的数据流经过文件描述符0,输出的标准流经过文件描述符1,2.
其次:close(0)即将标准输入的连接挂断。则当前文件描述符数组的第一个元素现在处于空闲状态。
最后:使用open(filename,O_RDONLY)打开一个想连到stdin上的文件。根据最低可用描述符原则,打开的文件被连接到标准输入上。
例如:
#include <stdio.h>
#include <fcntl.h>
main()
{
int fd ;
char line[100];
/* read and print three lines */
fgets( line, 100, stdin ); printf("%s", line );//从键盘上读取输出的字符串
fgets( line, 100, stdin ); printf("%s", line );
fgets( line, 100, stdin ); printf("%s", line );
/* redirect input */
close(0);
fd = open("/etc/passwd", O_RDONLY);
if ( fd != 0 ){
fprintf(stderr,"Could not open data as fd 0\n");
exit(1);
}
/* read and print three lines */
fgets( line, 100, stdin ); printf("%s", line );//从文件中读取输出字符串
fgets( line, 100, stdin ); printf("%s", line );
fgets( line