本文利用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编译应用程序:
运行: 可以看出,程序将hcg.mp3文件复制粘贴生成了 new_hcg.mp3文件, 文件大小一致