C++ 文件復制


 1 #include<iostream>
 2 #include<fstream>
 3 
 4 void copy(char* src, char* dst);
 5 int main()
 6 {
 7     using namespace std;
 8     char src[50] = "E:/test/jdk-8u121-windows-x64.exe";
 9     char dst[50] = "E:\\test\\jdk-8u121-windows-x64_bak.exe";
10     copy(src, dst);
11     
12     return 0;
13 }
14 
15 void copy(char* src, char* dst)
16 {
17     using namespace std;
18     ifstream in(src,ios::binary);
19     ofstream out(dst,ios::binary);
20     if (!in.is_open()) {
21         cout << "error open file " << src << endl;
22         exit(EXIT_FAILURE);
23     }
24     if (!out.is_open()) {
25         cout << "error open file " << dst << endl;
26         exit(EXIT_FAILURE);
27     }
28     if (src == dst) {
29         cout << "the src file can't be same with dst file" << endl;
30         exit(EXIT_FAILURE);
31     }
32     char buf[2048];
33     long long totalBytes = 0;
34     while(in)
35     {
36         //read從in流中讀取2048字節,放入buf數組中,同時文件指針向后移動2048字節
37         //若不足2048字節遇到文件結尾,則以實際提取字節讀取。
38         in.read(buf, 2048);    
39         //gcount()用來提取讀取的字節數,write將buf中的內容寫入out流。
40         out.write(buf, in.gcount());    
41         totalBytes += in.gcount();
42     }
43     in.close();
44     out.close();
45 }

 


免責聲明!

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



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