程序运行

程序运行

1 理解test.c, 说出程序功能
2 编译运行程序,提交运行截图

test.c的程序功能

#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);//open打开文件data,连接到stdin上

	newfd = dup2(fd,0);//newfd与fd关联的文件关联起来,让本来指向标准输出缓冲区的描述符0指向文件data	
	
	if ( newfd != 0 ){
		fprintf(stderr,"Could not duplicate fd to 0\n");
		exit(1);
	}
	close(fd);///关闭fd,这时候任何想从标准输入读取数据的函数都将从次文件中读入。		

	fgets( line, 100, stdin ); printf("%s", line );
	fgets( line, 100, stdin ); printf("%s", line );
	fgets( line, 100, stdin ); printf("%s", line );
}

  • 首先读取三次用户输入的字符串打印出来。
  • 以只读的方式打开data文件,记为fd。
  • 用newfd关联fd关联的文件并打印用户输入,若失败,输出“不能复制fd”。

编译运行程序

data

运行结果

posted @ 2021-12-13 11:37  绒绒的欧嘛harper  Views(57)  Comments(0Edit  收藏  举报
*/