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