c++ 通過數據流方式實現文件拷貝


#include "stdafx.h"
#include <iostream>
#include<fstream>
using namespace std;
void copy(char* src, char* dst);

int _tmain(int argc, _TCHAR* argv[])
{

    // 源文件地址及文件名
    char src[50] = "D:/cAddProgram/source_file/file.txt";

   // 拷貝的目的及文件名稱
    char dst[50] = "D:\\cAddProgram\\source_file\\file1.txt";

    copy(src, dst);

    return 0;
}

// 文件拷貝實現方法
void copy(char* src, char* dst)
{
    using namespace std;
    ifstream in(src,ios::binary);
    ofstream out(dst,ios::binary);
    if (!in.is_open()) {
        cout << "error open file " << src << endl;
        exit(EXIT_FAILURE);
    }
    if (!out.is_open()) {
        cout << "error open file " << dst << endl;
        exit(EXIT_FAILURE);
    }
    if (src == dst) {
        cout << "the src file can't be same with dst file" << endl;
        exit(EXIT_FAILURE);
    }
    char buf[2048];
    long long totalBytes = 0;
    while(in)
    {
        //read從in流中讀取2048字節,放入buf數組中,同時文件指針向后移動2048字節
        //若不足2048字節遇到文件結尾,則以實際提取字節讀取。
        in.read(buf, 2048);    
        //gcount()用來提取讀取的字節數,write將buf中的內容寫入out流。
        out.write(buf, in.gcount());    
        totalBytes += in.gcount();
    }
    in.close();
    out.close();
}



免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM