程序运行

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

#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 );
}

运行截图

未创建data时

data的内容

程序功能

fd=open(“文件名”,只读)
打开失败则返回0,所以未创建data文件时打印fd为0
先打印三行屏幕标准输入
然后打印data文件里的前三行
若未创建data则只打印屏幕输入前三行

posted @ 2021-12-13 11:34  20191223张俊怡  阅读(34)  评论(0编辑  收藏  举报