前一段时间选用mmap完结了一个文件的仿制操作,现在选用linux的I/O完结文件的仿制,根本的思维是将文件仿制到一个通用的buf中,然后将buf中的数据仿制到新的文件中。这种方法比较简单了解,可是也是底层的体系调用,主张少用,但有时分有必要选用(设备驱动)。
#include
#include
#include
#include
#include
#include
/*操作的根本权限*/
#define DEF_MODE S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH|S_IWOTH
int main()
{
/*源文件*/
int fdsrc = open(“/home/gong/program/cprogram/Test.c”,O_RDONLY,0);
if(fdsrc==-1)
{
printf(“error!!!”);
exit(-1);
}
/*取得源文件的巨细*/
struct stat statbuf;
fstat(fdsrc,&statbuf);
int length = statbuf.st_size;
/*意图文件*/
int fddst = open(“/home/gong/program/cprogram/copydata.c”,O_CREAT|O_RDWR,DEF_MODE);
if(fddst==-1)
{
printf(“error!!!”);
exit(-1);
}
/*完结根本的文件内容仿制进程*/
/*根本的思维便是将数据首要仿制到一个巨细适宜的buf中,然后将buf其间的内容写到给文件2*/
/*每一次都读入buf中,然后写buf的数据到文件2中*/
char buf[1024];/*buf巨细*/
char *p = buf;/*指向buf的指针*/
/*长度计算*/
int rlength=0,Rlength = 0;
int wlength=0;
while(length > 0)
{
/*先读后先的进程*/
rlength = read(fdsrc,p,1024);
Rlength = rlength;
while(rlength > 0)/*保证每次读出来的悉数写入到文件中*/
{
wlength = write(fddst,p,rlength);
rlength -= wlength;/*检测还有多少没有被仿制*/
p += wlength;/*移动指针到没有写入的区域*/
}
p = buf;/*保证每次都是仿制到buf中*/
length -= Rlength;
}
/*封闭文件*/
close(fdsrc);
close(fddst);
exit(0);
}
编译调试:
[gong@Gong-Computer cprogram]$ gcc -g copyFile.c -o copyFile
[gong@Gong-Computer cprogram]$ ./copyFile
/*Test.c*/
#include
#include
#include
#include
/*
char * returnstring(char *string)
{
//static char buffer[1024];
char * buffer = (char *)malloc(1024);
strcpy(buffer,string);
return buffer;
}*/
typedef int (*array10)[10];/*array100能够作为 int a[100]的指针*/
int main()
{
/*
int a = 10;
int *p = &a;
long int apple = 0;
apple = sizeof(int) * p;
printf(“The Number of apple is %ld”,apple);
*/
int a[10];
int i = 0;
for(i = 0;i<10;++i)
{
a[i] = i;
}
array10 b = a;
“copydata.c” 47L, 618C /*这阐明阐明仿制成功了,在文件中完结了数据的仿制*/
….
以上的代码阐明晰根本完结了文件的仿制,后期将选用规范I/O完结文件的仿制。需求留意的是Linux I/O主要是返回了完结的数据量,这个能够便利操作。文件的仿制进程是一个常用的进程。可是操作的方法存在一些不同,具体问题具体分析。