在某些情況下,我們可能會有獲取文本文檔(txt文件)的總行數的需求。常規的做法是通過fileread,一行一行的讀,然後統計累加行數,這樣的做法是逼不得已的做法,因為我們都曉得它的效率有多低。
其實,可以將文本文檔(txt文件)當成數據庫文件來處理,這樣就可以通過sql語句簡單快速的獲取文本文檔(txt文件)的總行數了。
[csharp]
global function long f_txt_rowcount (string as_file);
//獲取txt文件as_file的行數 by yyoinge 20111102
if not fileexists(as_file) then return -1
string ls_path, ls_file, ls_ext //路徑、文件名(不帶後綴)、後綴名
long ll_rowcount
//(1)分隔傳入的文件名
if posw(as_file, '.') = 0 or posw(as_file, '\') = 0 then return -1 //傳入的文件名有誤
ls_path = leftw(as_file,lenw(as_file) - posw(reverse(as_file), '\') + 1) //文件路徑
ls_file = rightw(as_file,posw(reverse(as_file), '\') - 1) //文件名(帶後綴)
ls_ext = midw(ls_file, posw(ls_file, '.') + 1) //後綴名
ls_file = leftw(ls_file, posw(ls_file, '.') - 1) //文件名(不帶後綴)
//(2)連接txt文件
oleobject rs, conn
rs = create oleobject
if rs.connecttonewobject("ADODB.Recordset") <> 0 then
destroy rs
messagebox('', '無法連接【ADODB.Recordset】!')
return -1
end if
conn = create oleobject
if conn.connecttonewobject("ADODB.Connection") <> 0 then
destroy rs
destroy conn
messagebox('', '無法連接【ADODB.Connection')
return -1
end if
//conn.Open("Driver={Microsoft Text Driver (*.txt; *.csv)};Dbq=" + ls_path + ';Extensions=' + ls_ext + ';')
conn.Open("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + ls_path + ';Extended Properties="text;HDR=No";')
//rs.Open("select 1 from [" + ls_file + "#" + ls_ext + "]", conn, 3,3, 1)
//ll_rowcount = long(rs.RecordCount())
//下面這種方法快一些
rs.Open("select count(1) from [" + ls_file + "#" + ls_ext + "]", conn, 3,3, 1)
ll_rowcount = long(rs.GetString(2, 1))// + 1用
rs.close()
conn.close()
destroy rs
destroy conn
return ll_rowcount
end function
調用方法如下:
long ll_rowcount
ll_rowcount = f_txt_rowcount("e:\3.txt")
摘自 yyoinge的專欄