1.文件io操作习题

4-1 tee命令是从标准输入中读取数据,直至文件结尾,随后将数据写入标准输入和命令行参数所指定的文件。请使用I/O系统调用实现tee命令,默认情况下,若已存在命令行参数指定文件同名的文件tee命令会将其覆盖。如文件以存在,请实现-a命令行选项(tee -a file)在文件结尾出追加数据。

#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
int main(int argc,char *argv[])
{
#ifndef BUF_SIZE 
#define BUF_SIZE 1024
#endif
	char buf[BUF_SIZE];
	int inputFd,outputFd;	
	int openFlags;
	int numRead;
	mode_t filePerms;
	if(argc!=3||strcmp(argv[1],"--help"))
		printf("%s old-file new-file\n",argv[0]);
	inputFd=open(argv[1],O_RDONLY);
	if(inputFd==-1)
		perror("open inputFd fail");
	openFlags=O_CREAT|O_WRONLY|O_TRUNC;
	filePerms=S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IWOTH|S_IWOTH;
	outputFd=open(argv[2],openFlags,filePerms);
	if(outputFd==-1)
		perror("open outputFd fail");
	while((numRead=read(inputFd,buf,BUF_SIZE))>0)
		if(write(outputFd,buf,numRead)!=numRead)
			printf("could't write whole buffer\n");
	if(numRead==-1)
		perror("read fail");

if(close(inputFd)==-1)perror("close inputFd fail");if(close(outputFd)==-1)perror("close outputFd fail");return 0;}

4-2编写一个类似于cp的命令程序,当使用该程序复制一个包含空洞(连续的空字节)的普通文件时,要求目标文件的空洞与原文件保持一致。

#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
int main(int argc,char *argv[])
{
#ifndef BUF_SIZE 
#define BUF_SIZE 1024
#endif
	char buf[BUF_SIZE];
	int inputFd,outputFd;	
	int openFlags;
	int numRead;
	mode_t filePerms;
	if(argc!=3||strcmp(argv[1],"--help"))
		printf("%s old-file new-file\n",argv[0]);
	inputFd=open(argv[1],O_RDONLY);
	if(inputFd==-1)
		perror("open inputFd fail");
	openFlags=O_CREAT|O_WRONLY|O_TRUNC;
	filePerms=S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IWOTH|S_IWOTH;
	outputFd=open(argv[2],openFlags,filePerms);
	if(outputFd==-1)
		perror("open outputFd fail");
	/*遇到eof(-1)时返回0,空洞部分为0,所以空洞部分不影响继续读取*/
	while((numRead=read(inputFd,buf,BUF_SIZE))>0)
		if(write(outputFd,buf,numRead)!=numRead)
			printf("could't write whole buffer\n");
	if(numRead==-1)
		perror("read fail");
	if(close(inputFd)==-1)
		perror("close inputFd fail");
	if(close(outputFd)==-1)
		perror("close outputFd fail");
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值