Shell命令编写——查看文件的命令cat

论坛 期权论坛 编程之家     
选择匿名的用户   2021-6-2 20:22   4510   0
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>

#define BUFFERSIZE 4096

int main(int ac,char *av[]){
 
 /*创建输入文件的文件描述符*/
 int in_fd;

 /*成功读取的字符串的长度*/
 int n_chars;

 /*字符缓冲区数组*/
 char buf[BUFFERSIZE];


 /*对输入时的参数进行判定*/
 if(ac != 2){
  fprintf(stderr,"usage: %s source destination\n",*av);
  exit(0);
 }
 

 /*打开要查看的文件*/
 if((in_fd=open(av[1],O_RDONLY))==-1){
  printf("Can not open:%s\n",av[1]);
  exit(1);
 }

 /*首先从第一个文件中读取一行数据,返回读取的长度*/
 while((n_chars = read(in_fd,buf,BUFFERSIZE))>0){

 /*按照读取的数据长度将缓冲区的数据输出到标准输出*/
  if(write(1,buf,n_chars)!=n_chars){
   printf("Write error to\n");
   exit(1);
  }
 }


 /*关闭两个文件*/
 if(close(in_fd)==-1){
  printf("Error close files\n"); 
  exit(1);
 }
 return 0;
}

分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:3875789
帖子:775174
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP