简体   繁体   中英

I made program that copies data from one file and pastes to another using (read,write) but i think its taking too long

i need to copy 1gb file to another and i am using this code while using different buffers (1byte, 512byte and 1024byte) while using 512byte buffer it took me about 22seconds but when i use 1byte buffer copying doesnt end even after 44minutes. Is that time expected or mby something is wrong with my code

#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;
}

Yes, this is expected, because system calls are expensive operations, so the time is roughly proportional to the number of times you call read() and write() . If it takes 22 seconds to copy with 512-byte buffers, you should expect it to take about 22 * 512 seconds with 1-byte buffers. That's 187 minutes, or over 3 hours.

This is why stdio implements buffered output by default.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM