![](/img/trans.png)
[英]Read/write program in c that copies file and i think its taking too long to copy
[英]I made program that copies data from one file and pastes to another using (read,write) but i think its taking too long
我需要将 1gb 文件复制到另一个文件,我在使用不同的缓冲区(1 字节、512 字节和 1024 字节)时使用此代码,而使用 512 字节缓冲区大约需要 22 秒,但是当我使用 1 字节缓冲区复制时,即使在 44 分钟后也不会结束。 那个时间是预期的还是我的代码有问题
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <corecrt_io.h>
int main(int argc, char* argv[])
{
char sourceName[20], destName[20], bufferStr[20];
int f1, f2, fRead;
int bufferSize = 0;
char* buffer;
/*printf("unesite buffer size(u bytima): ");
scanf("%d", &bufferSize);*/
//bufferSize = argv[3];
bufferSize = atoi(argv[3]);
buffer = (char*)calloc(bufferSize, sizeof(char));
/*printf("unesite source name: ");
scanf("%s", sourceName);*/
strcpy(sourceName, argv[1]);
f1 = open(sourceName, O_RDONLY);
if (f1 == -1)
printf("something's wrong with oppening source file!\n");
else
printf("file opened!\n");
/*printf("unesite destination name: ");
scanf("%s", destName);*/
strcpy(destName, argv[2]);
f2 = open(destName, O_CREAT | O_WRONLY | O_TRUNC | O_APPEND);
if (f2 == -1)
printf("something's wrong with oppening destination file!\n");
else
printf("file2 opened!");
fRead = read(f1, buffer, bufferSize);
while (fRead != 0)
{
write(f2, buffer, bufferSize);
fRead = read(f1, buffer, bufferSize);
}
return 0;
}
是的,这是意料之中的,因为系统调用是昂贵的操作,所以时间大致与调用read()
和write()
的次数成正比。 如果使用 512 字节缓冲区进行复制需要 22 秒,那么使用 1 字节缓冲区需要大约22 * 512
秒。 那是 187 分钟,或超过 3 个小时。
这就是stdio
默认实现缓冲输出的原因。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.