先交代一下背景,工作需要,開發環境發生了變更,數十個程式源**全部亂碼,(小廠ide只支援一種編碼),身為程式設計師,讓我乙個個檔案新建、複製、貼上是不存在的,祭出我的matlab才是王道。
第一步,先把所有文字檔案讀出來。
檢視結果,沒有問題,返回值是結構體,每個檔案對應乙個結構體,判斷f的維度即可知道檔案數目。f =
dir(startpath)
所以呢,f_num = length(f);
ok,f_num就是目錄裡面檔案的個數了。接下來出來目錄巢狀的問題,把目錄和檔案區分開來,研究dir()返回的結構體,有isdir項,很好,經過驗證,isdir 為1說明物件是目錄,為0說明物件是檔案。這就好辦了,是檔案的化只需要把檔案記錄下來,是目錄的化就遞迴**。
**如下:
這裡檔案判斷從第三個物件開始因為所有目錄的第乙個物件為目錄本身,第二個物件為它的上一級目錄。function filesearch
(startpath)
f =dir
(startpath)
;f_num =
length
(f);
for i =
3: f_num
subpath =
strcat(f
(i).folder,"\",
f(i)
.name);if
(f(i).isdir)
filesearch
(subpath)
;else
f(i)
.name
endend
儲存函式,然後呼叫該函式即可。
接下來實現檔案轉碼操作,檔案轉碼用簡單粗暴的方法,把原始檔開啟,然後新建乙個檔案,指定編碼,把原始檔的內容複製進去。filesearch
("f:\workspace\fpga\servo\src_rtl\")
具體操作如下,使用fopen讀把原始檔開啟,開啟的時候指定該檔案的編碼,然後同時開啟另乙個檔案,指定想要的新編碼,然後使用fgetl逐行讀取,使用fprintf逐行寫入新檔案。
**如下:
最後,實現批量轉碼,在之前寫的檔案讀取函式裡面呼叫轉碼函式。並對目錄結構進行處理,複製檔案的同時複製目錄結構。function codetransfer
(rsc,dst,rsc_encode,dst_encode)
frsc =
fopen
(rsc,
'r',
'n',rsc_encode)
;fdst =
fopen
(dst,
'w',
'n',dst_encode)
;%a =
fread
(rsc,
'*char'
)';while(1
) tmp =
fgetl
(frsc)
if(tmp ==-1
)break
; end
fprintf
(fdst,
"%s\n"
,tmp)
;end
fclose
(frsc)
;fclose
(fdst)
;
在函式傳入引數加上搜尋內容根目錄以及目標內容根目錄引數,然後使用dir()搜尋根目錄,逐個判斷搜尋結果,若搜尋到目錄則在目標內容根目錄建立同名目錄,然後遞迴進該目錄,若搜尋到檔案,則開始檔案複製。
更新後**如下:
開乙個新m檔案,呼叫函式function filesearch
(startpath,rscpath,dstpath)
f =dir
(startpath)
;f_num =
length
(f);
for i =
3: f_num
subpath =
strcat(f
(i).folder,"\",
f(i)
.name);if
(f(i).isdir)
newpath =
strrep
(subpath,rscpath,dstpath)
;mkdir
(newpath)
;filesearch
(subpath,rscpath,dstpath)
;else
rscfilepath =
strcat(f
(i).folder,"\",
f(i)
.name)
; dst_filepath =
strrep
(subpath,rscpath,dstpath)
;codetransfer
(rscfilepath,dst_filepath,
'utf-8'
,'gbk');
endend
ok,「f:\workspace\xx"目錄被成功複製到"f:\workspace\xxbak」,且所有檔案轉碼完成。rscpath = "f:\workspace\xx\";
dstpath = "f:\workspace\xxbak\";
filesearch
(rscpath,rscpath,dstpath)
;
MATLAB順序讀取資料夾資料
matlab sequentially read folder data 通過順序讀取資料夾內的資料,可以實現matlab對不同資料進行批量處理分析,可以極高的提高效率。具體方法 filedir uigetdir 通過ui介面獲取資料夾位置 list dir fullfile filedir 將資料...
matlab遍歷資料夾
這又是個matlab程式,上次幫同學寫了個提取序列的函式,這次要能自動將資料夾中所有檔案自動的識別並建立對應的資料夾,資料夾名要和檔案中某個字段相同。tmp1 mkdir dir final system tmp1 資料夾建立完成 我試了下,用下面的函式系統就自動關機了,fun shutdown s...
matlab檔案 資料夾操作
定義路徑 f fullfile c download pwd 返回當前路徑cd c toolbox matlab demos 切換當前工作目錄到demos cd 切換當前工作目錄到matlabboolean isfolder f boolean isempty f files dir f files...