数据文件定位
MATLAB提供了与文件定位操作有关的函数fseek和ftell。fseek函数用于定位文件位置指针,其调用格式为:
status=fseek(fid, offset, origin)
其中fid为文件句柄,offset表示位置指针相对移动的字节数,OFFSET values are interpreted as follows:
> 0 Move toward the end of the file. = 0 Do not change position.
< 0 Move toward the beginning of the file.
origin表示位置指针移动的参照位置,ORIGIN values are interpreted as follows:
'bof' or -1 Beginning of file
'cof' or 0 Current position in file
'eof' or 1 End of file。若定位成功,status返回值为0,否则返回值为–1。 ftell函数返回文件指针的当前位置,其调用格式为: position=ftell (fid)
返回值为从文件开始到指针当前位置的字节数。若返回值为–1表示获取文件当前位置失败。
例:
FID=fopen('sw.m','r') fseek(FID,10,-1) ans = 0
>> ftell(FID) ans = 10
>> fseek(FID,-10,1) ans = 0
>> ftell(FID) ans =
2180
文件指针可以移动到当前文件末尾的后面,但不能移动到开头的前面;当把指针移动到文件末尾后面时,若关闭文件则文件大小会自动增长到文件指针所指的大小,用这种方法可以很容易创建一个很大的文件,当然新增加的文件内容是随机的。