Faster way to move file in c++ on linux

折月煮酒 提交于 2019-12-10 14:06:57

问题


I'm trying to move files on linux by using C++. The Problem is, that the source file and the destination folder can be in different partitions. So I can't simply move the files. Ok. I decided to copy the file and delete the old one.

//-----
bool copyFile(string source, string destination)
{
    bool retval = false;
    ifstream srcF (source.c_str(), fstream::binary);
    ofstream destF (destination.c_str(), fstream::trunc|fstream::binary);
    if(srcF.is_open() && destF.is_open()){
        destF << srcF.rdbuf(); //copy files binary stream
        retval = true;
    }
    srcF.close();
    destF.close();
    return retval;
}
//-----

Now my problem. I realized, this method is very slow. It takes 47 seconds for 100MB. Simply copy a file with the console command takes 2-3 seconds.

Does anybody have an idea?


回答1:


Streams are known to be pretty slow. You can either use tools provided by operating system or you can use some portable wrapper.

I would recommend boost::filesystem, because it is planned to be added to STL (C++14 ?).

Documentation here: boost::filesystem::copy_file().




回答2:


Using Linux - rename(old name, new name);



来源:https://stackoverflow.com/questions/19565085/faster-way-to-move-file-in-c-on-linux

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!