#include <stdio.h> #include <stdlib.h> #include <fcntl.h> main() { int fd ; int newfd; char line[100]; fgets( line, 100, stdin ); printf("%s", line ); fgets( line, 100, stdin ); printf("%s", line ); fgets( line, 100, stdin ); printf("%s", line ); fd = open("data", O_RDONLY); newfd = dup2(fd,0); if ( newfd != 0 ){ fprintf(stderr,"Could not duplicate fd to 0\n"); exit(1); } close(fd); fgets( line, 100, stdin ); printf("%s", line ); fgets( line, 100, stdin ); printf("%s", line ); fgets( line, 100, stdin ); printf("%s", line ); }
首先先新建一个文件,里面输入我的学号,然后运行程序。我输入数字,程序会打印我输入的数字。输入三遍后程序会打印我刚刚新建文件里的内容