前言#
今天來看一個和這個IO
系列格格不入的函數,為什么說他格格不入呢,因為他必須使用顯示的文件描述符,而不能使用io.xxxx
這樣的形式,實際上這個函數也是文件操作中使用比較多的函數,用來控制文件的的讀/寫指針,也就是讀/寫的位置,控制了文件中最后的內容形式。
內容#
file:seek()##
- 原型:file:seek([whence][,offset])
- 解釋:設置和獲取當前文件位置,成功則返回最終的文件位置(按字節),失敗則返回
nil
加錯誤信息,其中參數offset表示偏移的字節數,默認為0,whence是一個描述參數的字符串,一共有下述3中取值:- "set":設置從文件頭開始
- "cur": 設置從當前位置開始[默認]
- "end": 設置從文件尾開始
Usage##
- 首先新建一個文件命名為seektest.lua然后編寫如下代碼:
-- 打開文件
local myfile = io.open("seektest.txt", "w")
if nil == myfile then
print("open file seektest.txt fail")
end
-- 記錄文件開始位置
local beginpos = myfile:seek()
print("file begin pos = "..beginpos)
-- 向后移動100個字節
local movehundred = myfile:seek("cur", 100)
print("after move hundred file pos = "..movehundred)
-- 回退95個字節,開始輸入內容
local moveback = myfile:seek("cur", -95)
print("after move back file pos = "..moveback)
myfile:write("file begin......................")
myfile:write("................................")
-- 向后移動20字節,插入內容
myfile:seek("set", 20)
myfile:write("\nthis is insert content\n")
-- 從后回退15字節插入內容
myfile:seek("end", -15)
myfile:write("\nbingo end")
-- 記錄此文件大小
local curfilesize = myfile:seek("end")
print("cur file size = "..curfilesize)
-- 結尾向后擴大10字節插入內容
myfile:seek("end", 10)
myfile:write("test")
-- 記錄最終文件大小作比較
local finalfilesize = myfile:seek("end")
print("final file size = "..finalfilesize)
-- 移動文件指針到開頭
myfile:seek("set")
myfile:write("haha ")
myfile:close();
myfile = io.open("seektest.txt", "r")
-- 讀取文件內容
local content = myfile:read("*a");
myfile:close();
-- 打印內容
print("\nfile content is:")
print(content)
- 運行結果
io_seek.png
總結#
- 不帶參數file:seek()則返回當前位置,
file:seek("set")
則定位到文件頭,file:seek("end")
則定位到文件尾并返回文件大小。 - 參數
whence
的默認值是"cur"
,而參數offset
的默認值是0。 - 由代碼可知參數
offset
可以是負數表示向前移動。 - 分析一下結果中為什么沒有輸出空白的部分和字符“test”呢,原因是中間有一段是沒有內容的,這段內容的默認是我們不知道是什么,因為這是我們直接跳過的,所以在輸出時字符串被截斷了,導致字符串“test”沒有顯示出來。
- 我借助其他文本工具顯示出最后的一段空白字符是
NULL
,也就是'\0'
,這也就解釋了為什么最后的“test”內容被截斷了。