复制基本思路。
1.打开第一个文件。
2.读取第一个文件的内容。
3.打开/创建第二个文件。
4.将文件写入进去。
源代码
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<unistd.h>
#include<string.h>
#include<stdio.h>
#include<stdlib.h>
int main(int argc,char **argv)
{
if(argc != 3)
{
printf("param error\n");
exit(-1);
}
int fdarg;
fdarg = open(argv[1],O_RDWR);
int size = lseek(fdarg,0,SEEK_END);
lseek(fdarg,0,SEEK_SET);
char *readbuf;
readbuf = (char*)malloc(sizeof(char)*size+8);
read(fdarg,readbuf,size);
int fades;
fades = open(argv[2],O_RDWR|O_CREAT|O_TRUNC,0600);
Write(fades,redbuf,strlen(readbuf));
close(fdarg);
close(fades);
return 0;
}
带参数的main。
1.第一个参数argc是外部输入的参数个数。
2.第二个参数argv[ ]是参数的字符串数组。
int main(int argc,char **argv)
{
if(argc != 3)
{
printf("param error\n");
exit(-1);
}
1.打开第一个文件。
int fdarg;
fdarg = open(argv[1],O_RDWR);
2.计算内容的长度。
1.使用lseek函数将光标指向数据末尾,用size 来接受lseek的返回值(起始地址的偏移值),然后再次使用该函数将光标指向起始位置。
int size = lseek(fdarg,0,SEEK_END);
lseek(fdarg,0,SEEK_SET);
3.保存第一个文件的内容。
使用read读取刚刚保存在size里面的内容,并保存到缓冲区。
char *readbuf;
readbuf = (char*)malloc(sizeof(char)*size+8);
read(fdarg,readbuf,size);
4.打开/创建第二个文件。
打开/创建第二个文件,赋予权限,可读可写,追加权限每次写入都把之前的清空。
int fades;
fades = open(argv[2],O_RDWR|O_CREAT|O_TRUNC,0600);
5.写入内容。
使用write函数将刚刚保存在缓冲区的内容读写进来。
Write(fades,redbuf,strlen(readbuf));
6.关闭文件。
close(fdarg);
close(fades);