
洋葱码农 - 云代码空间
—— 一直在改,从未有变
_图1
_图2
_图3
_图4
_图5/* stdinredir1.c
* purpose: show how to redirect standard input by replacing file
* descriptor 0 with a connection to a file.
* action: reads three lines from standard input, then
* closes fd 0, opens a disk file, then reads in
* three more lines from standard input
*/
#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, 100, stdin ); printf("%s", line );
}
【方法二】:【open】-【close】-【dup】-【close】
_图6/* stdinredir2.c
* shows two more methods for redirecting standard input
* use #define to set one or the other
*/
#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 );
fgets( line, 100, stdin ); printf("%s", line );
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 );
fgets( line, 100, stdin ); printf("%s", line );
fgets( line, 100, stdin ); printf("%s", line );
}
【方法三】:【open】-【dup2】-【close】。