fseek
移至文件中的指定位置
说明
示例
移动到文件中的新位置
打开下面的 badpoem.txt
文件,执行读取操作(使位置指针前进),然后使用 seek
移动到文件中的新位置。
使用 fopen
打开文件。然后,使用 ftell
查询当前位置。
fid = fopen('badpoem.txt');
ftell(fid)
ans = 0
读取前三行,并在每次读取后查询指针在文件中的位置。使用 fgetl
进行读取,在读取操作后使用 fseek
检查当前位置。
tline1 = fgetl(fid) % read the first line
tline1 = 'Oranges and lemons,'
ftell(fid)
ans = 20
读取第二行并检查当前位置。
tline2 = fgetl(fid) % read the second line
tline2 = 'Pineapples and tea.'
ftell(fid)
ans = 40
读取第三行并检查当前位置。
tline3 = fgetl(fid) % read the third line
tline3 = 'Orangutans and monkeys,'
ftell(fid)
ans = 64
要读取第 2 行,请将文件中的位置设置为指向第 2 行的开头。使用 fseek
设置位置,然后执行读取操作。
fseek(fid,20,'bof');
fgetl(fid)
ans = 'Pineapples and tea.'
关闭文件。
fclose(fid);
输入参数
fileID
— 文件标识符
整数
已打开文件的文件标识符,指定为整数。在使用 fseek
之前,必须使用 fopen
打开文件并获取其 fileID
。
数据类型: double
offset
— 字节数
整数
要相对于 origin
移动的字节数,指定为整数。offset
的值可以为正数、负数或零。
数据类型: double
origin
— 起始位置
整数 | 字符向量 | 字符串
文件中的起始位置,指定为字符向量、字符串标量或数值标量。
| 文件的开头 |
| 文件中的当前位置 |
| 文件的结尾 |
数据类型: double
| char
| string
提示
如果一个文件有
n
个字节的数据,则这n
个字节位于从0
到n-1
的位置。
备选方法
要移至文件的开头,请调用
frewind(fileID)
此调用等同于
fseek(fileID, 0, 'bof')
扩展功能
C/C++ 代码生成
使用 MATLAB® Coder™ 生成 C 代码和 C++ 代码。
用法说明和限制:
当 MATLAB® 的行为与 C 编译器的行为不同时,生成的代码将与 C 编译器的行为相匹配。示例包括:
跳过文件末尾查找。
不在使用追加访问权限打开的文件末尾进行查找。
偏移量作为有符号长数据类型传递给 C 运行时环境。因此,偏移值必须适合目标硬件上的长数据类型。
基于线程的环境
使用 MATLAB® backgroundPool
在后台运行代码或使用 Parallel Computing Toolbox™ ThreadPool
加快代码运行速度。
此函数完全支持基于线程的环境。有关详细信息,请参阅在基于线程的环境中运行 MATLAB 函数。
版本历史记录
在 R2006a 之前推出R2022b: 在基于线程的环境中使用函数
此函数支持基于线程的环境。
MATLAB 命令
您点击的链接对应于以下 MATLAB 命令:
请在 MATLAB 命令行窗口中直接输入以执行命令。Web 浏览器不支持 MATLAB 命令。
Select a Web Site
Choose a web site to get translated content where available and see local events and offers. Based on your location, we recommend that you select: .
You can also select a web site from the following list:
How to Get Best Site Performance
Select the China site (in Chinese or English) for best site performance. Other MathWorks country sites are not optimized for visits from your location.
Americas
- América Latina (Español)
- Canada (English)
- United States (English)
Europe
- Belgium (English)
- Denmark (English)
- Deutschland (Deutsch)
- España (Español)
- Finland (English)
- France (Français)
- Ireland (English)
- Italia (Italiano)
- Luxembourg (English)
- Netherlands (English)
- Norway (English)
- Österreich (Deutsch)
- Portugal (English)
- Sweden (English)
- Switzerland
- United Kingdom (English)