将stdin定向到文件
1. close(0),即将标准输入的连接断开
2. open(filename, O_RDONLY)打开一个想连接到stdin上的文件。当前的最低可用文件描述符是0,所以打开的文件将被连接到标准输入上去。这时候任何想从标准输入读取数据的函数都将从次文件中读入。
第二种方法:
1. fd=open(file),打开stdin将要重定向的文件,这时候文件的描述符不是0,因为0被stdin占据。
2. close(0), 现在0已经空闲
3. dup(fd), 将fd做一个复制,这时候将使用文件描述符0,也就是将打开的文件和文件描述符0也关联起来。这时候文件有两个描述符号,fd和0
4. close(fd), 关闭fd,这时候任何想从标准输入读取数据的函数都将从次文件中读入。
1. close(0),即将标准输入的连接断开
2. open(filename, O_RDONLY)打开一个想连接到stdin上的文件。当前的最低可用文件描述符是0,所以打开的文件将被连接到标准输入上去。这时候任何想从标准输入读取数据的函数都将从次文件中读入。
#include <stdio.h>
#include <fcntl.h>
main()
{
int fd ;
char line[100];
/* read and print three lines */
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 );
}
1. fd=open(file),打开stdin将要重定向的文件,这时候文件的描述符不是0,因为0被stdin占据。
2. close(0), 现在0已经空闲
3. dup(fd), 将fd做一个复制,这时候将使用文件描述符0,也就是将打开的文件和文件描述符0也关联起来。这时候文件有两个描述符号,fd和0
4. close(fd), 关闭fd,这时候任何想从标准输入读取数据的函数都将从次文件中读入。
#include <stdio.h> #include <fcntl.h> /* #define CLOSE_DUP /* open, close, dup, close */ /* #define USE_DUP2 /* open, dup2, close */ main() { int fd ; int newfd; char line[100]; /* read and print three lines */ fgets( line, 100, stdin ); printf("%s", line ); /* redirect input */ fd = open("data", O_RDONLY); /* open the disk file */ #ifdef CLOSE_DUP close(0); newfd = dup(fd); /* copy open fd to 0 */ #else newfd = dup2(fd,0); /* close 0, dup fd to 0 */ #endif if ( newfd != 0 ){ fprintf(stderr,"Could not duplicate fd to 0\n"); exit(1); } close(fd); /* close original fd */ /* read and print three lines */ fgets( line, 100, stdin ); printf("%s", line ); }
强烈向大家推荐一个好网站,[url=http://www.51zxw.net/study.asp?vip=9533333][我要自学网][/url],教程由在校老师录制,,有办公类、平 面设计类,室内设计类,机械设计类教程.....让你足不出门,都可以体现学校的专业教育!