- 論壇徽章:
- 12
|
本帖最后由 523066680 于 2017-09-21 16:45 編輯
環境 XP/WIN7 Active Perl v5.16
編輯整理:523066680
原帖:http://code-by.org/viewtopic.php?f=17&t=131
專欄:https://zhuanlan.zhihu.com/PerlExample
以下主要討論用 ActivePerl 自帶的模塊的處理方法,更省心的辦法請參考2樓
由于常見的那些文件操作函數都不支持,為了達到目的,需要各種方法配合。
以下腳本代碼均保存為 utf8 編碼格式。
文件的建立
模塊: WIN32
use Win32;
use utf8;
#接受unicode傳參
Win32::CreateFile("W32CreateFile・測試"); |
特性: 成功時返回true,但不返回文件句柄
Creates the FILE and returns a true value on success.
Check $^E on failure for extended error information.
模塊:Win32API::File
函數:$hObject= CreateFileW( $swPath, $uAccess, $uShare, $pSecAttr, $uCreate, $uFlags, $hModel )
$hObject 即為文件句柄(對象)
注意事項:傳入的文件路徑的編碼格式為:UTF16-LE ,必須以\x00結尾。
示例代碼:
use Win32API::File qw(:ALL);
use utf8;
use Encode;
$str="文tes・t.txt\x00";
$hobject=CreateFileW(encode('UTF16-LE', $str), GENERIC_WRITE, 0, [], OPEN_ALWAYS,0,0); |
目錄的建立
模塊:Win32
use Win32;
use utf8;
Win32::CreateDirectory("Dir・測試"); |
枚舉文件復制某個文件夾內的文件
模塊:Win32API::File
如果先獲取文件的短名,然后再復制,目標文件名也會變成短名。
可先用 cmd /U 模式獲取文件列表,然后CopyFileW進行復制:
use Win32API::File qw':ALL';
use Encode;
use utf8;
my $src=encode('gbk','.\\測試目錄');
my $dst='.\\Target';
#該目錄只有一層,/s開關是為了列出完整的路徑
my $all=`cmd /U /C dir /s /b \"$src\"`;
my $fn;
for (split(/\x0d\x00\x0a\x00/, $all))
{
$fn = encode('gbk', decode('utf16-le',$_))."\n";
@xrr = split(/\x5c\x00/, $_);
CopyFileW(
$_ ."\x00",
encode('utf-16le', decode('utf8', "$dst\\")).$xrr[$#xrr]."\x00",
1
);
print "$^E\n" if ($^E);
} |
這里有幾個注意事項細節一、
正確地使用 split $all 截斷utf-16le字符段落,分隔符應為0d 00 0a 00
細節二、
如果用 basename() 分割路徑,同樣會遇到00被忽略的問題,'\\' 的U16LE
編碼是5C 00,但是basename 只按5C截斷,剩下的00造成了處理亂碼。
測試basename的第二個參數設置為 "\x5c\x00" 并不能解決這個問題
解決方法
手工去掉開頭處的 \x00
或者:
@xrr=split(/\x5c\x00/, $_);
細節三、
CopyFileW復制文件時,要在末尾加\x00作為字符串終止符,否則各種問題=_=
判斷文件是否存在
方法一:先轉為短名再判斷,不做贅述
方法二:渣方法,用CreateFileW測試建立同名文件,看是否有沖突
重命名
模塊:Win32API::File
MoveFileW(
encode('utf-16le', decode('utf8',$F))."\x00",
encode('utf-16le', decode('utf8',$newname))."\x00"
); |
獲取文件的日期信息
普通文件名的情況含有Unicode字符的文件名的情況
[How to stat a file with a Unicode (UTF16-LE) filename in Windows?](fhttp://www.perlmonks.org/?node_id=741797)
其中的方法是通過createfileW 獲取文件句柄,然后用OsFHandleOpen獲取通用的文件句柄對象,并傳入state
(感覺特別繞)
另一種就是先轉為短名再獲取日期,但是這種方法在處理文件量大的時候,效率非常低。
前面 perlmonks 中的方法效率要高得多
use utf8;
use Encode;
use Win32;
$filename='D:\測試目錄\董貞 ・ 01.劍如虹.[貞江湖].mp3';
$filename=Win32::GetShortPathName($filename);
my $mtime = (stat $filename)[9];
my($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime($mtime);
$year+=1900;
$mon+=1;
print "$year-$mon-$mday\n"; |
[Finished in 0.4s] |
Perl, Win32, Unicode, Perl, Win32, Unicode, Perl, Win32, Unicode, Perl, Win32, Unicode, Perl, Win32, Unicode, Perl, Win32, Unicode, Perl, Win32, U
評分
-
查看全部評分
|