C 檔案拷貝的一些

2021-09-24 23:50:08 字數 1663 閱讀 2271

【task】

做乙個控制台程式的demo,具備兩個引數輸入,乙個srcdir 乙個dstdir,都是字串資料夾位址型別,實現功能將srcdir位址的內的所有內容拷貝至dstdir中

【解決方案】

剛開始搜一些資料發現有很多用copyfile函式來拷貝檔案的,用法如下

copyfile("c:\\a.txt","c:\\b.txt",false);
只要輸入原始檔位址,以及目的檔案位址就可以了,知道了怎麼拷貝檔案,之前也寫過資料夾遍歷相關的**,所以拷貝資料夾就簡單很多了,只要開啟資料夾用檔案控制代碼遍歷拷貝就可以了,於是很快寫完,但是除錯的時候發現這個函式不是很友好。。。

問題1:copyfile函式定義如下,引數是lpcwstr型別的,而**中引數是string型別的,這兩個型別間無法直接轉換

copyfilew(

_in_ lpcwstr lpexistingfilename,

_in_ lpcwstr lpnewfilename,

_in_ bool bfailifexists

);

這是lpcwstr型別的定義,lpcwstr是乙個指向unicode編碼字串的32位指標,所指向字串是wchar型,而不是char型

typedef const wchar_t* lpcwstr;
於是搜到別人寫好的轉換方法(感謝),這個問題算是解決了:)

//從std::string轉換為lpcwstr

lpcwstr stringtolpcwstr(std::string orig)

問題2:當檔名中包含中文的時候,copyfile函式執行失敗,getlasterror()返回的異常為error_file_not_found,用vs2017斷點除錯發現執行時檔名會變成亂碼,所以找不到,沒有找到解決辦法,只能拋棄這個方法了,最後換成了用資料流方式實現,但在此徵集其他解決方案希望大家能告訴我:(

【附】可實現的完整**

#include#include#include#include#include#include using namespace std;

//拷貝資料夾

void copyfiles(string &srcpath, string &despath)

while (_findnext(handle, &fileinfo) == 0)

}} else

{ string srcfilepath = srcpath + "\\" + fileinfo.name;

string desfilepath = despath + "\\" + fileinfo.name;

ifstream in(srcfilepath, ios::binary);

ofstream out(desfilepath, ios::binary);

if (!in) {

cout<< "source file "<< fileinfo.name <<" open file error"<【參考】

1.c++ _copyfile拷貝檔案

2.c++實現資料夾的遞迴遍歷複製(包含子資料夾)---2018

3.c++ 從std::string轉換為lpcwstr

4.c++複製檔案

C 中一些檔案的操作

1.file.exist檢查檔案是否存在 public static bool exists string path 檔案存在時,返回true,相反返回false。2.讀寫檔案 public static string readalltext string path 讀取檔案的所有行放入乙個字串中,...

c 檔案的一些基本操作

一 對檔案的操作 1.基礎操作。對檔案操作需要 include 用ofstream 或 ifstream申明流變數 如data 申明流變數由於連線需要輸出的檔案 ofstream data 輸入的檔案 ifstream data 流變數連線 開啟 檔案 data.open 系統中的檔名 讀取檔案資料...

關於深拷貝和淺拷貝的一些見解。

簡單的複製,person p1 new person lisi 23 person p2 p1 system.out.println p1 p2 p2只是對p1的引用,還是指向同乙個位址。此時可以,選擇clone.person p1 new person zhangsan 23 person p2 ...