罗根勒曼小时候好可爱:标准IO与文件IO的效率的纵向比较
来源:百度文库 编辑:中财网 时间:2024/04/29 04:58:00
一.标准IO 实现copy (mycopy_fp.c)
#include
#include
#include
//确保设置的缓冲都为1024
#define BUF_SIZE 1024
int main(int argc, char *argv[])
{
FILE *fp_src;
FILE *fp_des;
char *buff;
long int filesize;
int count=0;
int diff;
clock_t start,finish;
start = clock();
if(argc != 3 )
{
perror("args");
return -1;
}
if((fp_src = fopen(argv[1], "r"))==NULL)
{
perror("fp_src");
return -1;
}
if((fp_des = fopen(argv[2], "w"))==NULL)
{
perror("fp_des");
return -1;
}
//主要是为了copy最后不到1024字节的内容
filesize = fseek(fp_src,0,SEEK_END);
if(fseek(fp_src,0,SEEK_SET) == -1)
{
perror("fseek");
return -1;
}
buff = (char *) malloc (BUF_SIZE);
while(fread(buff,BUF_SIZE,1,fp_src) == 1)
{
fwrite(buff,BUF_SIZE,1,fp_des);
count++;
}
diff = filesize - count*BUF_SIZE;//最后可能小于1024,但又不为0。
if(diff > 0)
{
fwrite(buff,diff,1,fp_des);
}
fclose(fp_src);
fclose(fp_des);
finish = clock();
printf("The programe use %ldms\n", (finish - start)/1000);
return 0;
}
二.文件IO 实现copy (mycopy_fd.c)
#include
#include
#include
#include
#include
#define BUF_SIZE 1024
int main(int argc, char *argv[])
{
int fd_src,fd_des;
char buff[BUF_SIZE];
ssize_t n;
clock_t start,finish;
start = clock();
if(argc != 3)
{
perror("argc");
return -1;
}
fd_src = open(argv[1],O_RDONLY);
if(fd_src == -1)
{
perror("open fd_src");
return -1;
}
fd_des = open(argv[2],O_CREAT|O_WRONLY|O_TRUNC|O_EXCL,0666);
if(fd_des == -1)
{
perror("open fd_des");
return -1;
}
while((n = read(fd_src,buff,BUF_SIZE)) != 0)
{
if(n == -1)
{
perror("read");
return -1;
}
if(write(fd_des,buff,n) == -1)
{
perror("write");
return -1;
}
}
close(fd_src);
close(fd_des);
finish = clock();
printf("The program use %ldms\n", (finish - start)/1000);
return 0;
}
三.对比效果