linux实现命令解释器_根据linux系统调用实现cp命令

本文利用linux系统调用中的open( )、read( )、write( ) 函数实现简易版的linux cp命令, 供学习嵌入式 linux系统编程的小伙伴们参考

/* 声明: 本代码只作为学习参考资料使用,不可作为其他用途,否则后果自负 */#include#include#include#include#include#include#include#ifndef BUF_SIZE#define BUF_SIZE 1024#endifint main(int argc, char *argv[]){   int inputFd, outputFd, openFlags;   mode_t filePerms;   ssize_t numRead;   char buf[BUF_SIZE];   if(argc !=3 || strcmp(argv[1],"--help") == 0)            printf("copy oldfile newfile \n\r");   /* open input and output file*/   inputFd = open(argv[1],O_RDONLY);   if(inputFd == -1)printf("opening file %s \n\r",argv[1]);     openFlags = O_CREAT | O_WRONLY | O_TRUNC;   filePerms = S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH |S_IWOTH; /* rw-rw-rw- */   outputFd = open(argv[2], openFlags, filePerms);   if(outputFd == -1)        printf("open file %s  \n\r",argv[2]);   /* Transfer data until we encunter end  of input or an error */   while(numRead = read(inputFd, buf, BUF_SIZE))        if(write(outputFd, buf, numRead) != numRead)           printf("couldn't write whole buffer \n\r");   if(numRead == -1)        printf("read error \n\r");   if(close(inputFd) == -1)      printf("close input error \n\r");   if(close(outputFd) == -1)      printf("close output error \n\r");   return 0;}

gcc编译应用程序:

51b128ca64411cae3300ba3c0d3f353b.png

运行:    可以看出,程序将hcg.mp3文件复制粘贴生成了 new_hcg.mp3文件, 文件大小一致

25016f75229cac334d22bbb619daf25e.png

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值