簡體   English   中英

我制作了從一個文件復制數據並使用(讀、寫)粘貼到另一個文件的程序,但我認為它花費了太長時間

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM