cp src.c des.c
实现思路:
- 打开src.c
- 读取src.c到buf
- 打开/创建des.c
- 将buf写入des.c
- close文件
int mian()参数介绍:
int main(int argc,char**argv)
{
//argc 表示有几个参数
//argv 数组的指针里面的每一项都是数组
以cp src.c des.c为例
argc = 3
cp argv[0]里面有数组char型cp 2个字符串以此类推
src.c argv[1]
des.c argv[2]
}
具体代码为例
#include<stdio.h>
int main(int argc, char **argv)
{
printf("total params:%d\n",argc);
printf("NO.1 params:%s\n",argv[0]);
printf("NO.2 params:%s\n",argv[1]);
printf("NO.3 params:%s\n",argv[2]);
return 0;
}
输入./a.out src.c des.c
返回:
total params:3
NO.1 params:./a.out
NO.2 params:src.c
NO.3 params:des.c
cp 代码的实现:
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
int main(int argc, char **argv)
{
int fdSrc;
int fdDes;
char *readbuf = NULL;
if(argc != 3){
printf("params error\n");
exit(-1);
}
fdSrc = open(argv[1],O_RDWR);
int size = lseek(fdSrc,0,SEEK_END); //用lseek去读取字节大小
lseek(fdSrc,0,SEEK_SET);//将光标移动到开头去读内容
readbuf = (char *)malloc(sizeof(char)*size+1);开辟空间
memset(readbuf,0,sizeof+1);//初始化赋值
int n_read = read(fdSrc,readbuf,size);
fdDes = open(argv[2],O_RDWR|O_CREAT|O_TRUNC,0600);
int n_write = write(fdDes,readbuf,strlen(readbuf));
close(fdSrc);
close(fdDes);
return 0;
}