方法一:利用系统底层调用逐个字节的拷贝往一个文件,源码:
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
int main()
{
char c;
int in, out; 
in = open("file.in", O_RDONLY);
out = open("file.out", O_WRONLY|O_CREAT, S_IRUSR|S_IWUSR);
while(read(in,&c,1) == 1)
write(out,&c,1);
exit(0);
}查看系统执行时间结果如下:

方法二:利用系统底层调用逐个数据块(M)的拷贝往一个文件,源码:
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
int main()
{
char block[1024];
int in, out;
int nread;
in = open("file.in", O_RDONLY);
out = open("file.out", O_WRONLY|O_CREAT, S_IRUSR|S_IWUSR);
while((nread = read(in,block,sizeof(block))) > 0)
write(out,block,nread);
exit(0);
}查看系统执行时间结果如下:

方法三:利用文件流进行拷贝:
#include <stdio.h>
int main()
{
int c;
FILE *in, *out;
in = fopen("file.in","r");
out = fopen("file.out","w");
while((c = fgetc(in)) != EOF)
fputc(c,out);
exit(0);
}

这一次,程序运行了0.007秒,不如底层系统调用以数据块为单位拷贝程序快,但比起那个底层以字符为单位拷贝的程序快太多了,这是因为在stdio库在FILE结构里使用了一个内部缓冲区,只有缓冲区满的时候才进行底层的调用。


浙公网安备 33010602011771号