我们着重看一下fgetl的实现,lt返回的是换行符的ASCII代码值,0D0A,所以fgetl是能够返回指定文件的下一行并删除换行符的,fgets读取时会保留换行符。 当textscan和fgetl配合使用的时候,会碰到以下情况,textscan读取数据之后,fgetl再读取数据读出来的是空值。 原因: texscan是一个需要指定格式和调用次数的函数,他对文件的操作并不是以换行符为分界线的,所以fgetl在textscan之后调用时,需要对遗留的换行符进行处理,所以每次fgetl会有一次返回空值的情况。
C = textscan(fileID,formatSpec,N)
function tline = fgetl(fid)
%FGETL Read line from file, discard newline character.
% TLINE = FGETL(FID) returns the next line of a file associated with file
% identifier FID as a MATLAB character vector. The line terminator is NOT included.
% Use FGETS to get the next line with the line terminator INCLUDED. If just an
% end-of-file is encountered, -1 is returned.
%
% If an error occurs while reading from the file, FGETL returns an empty character
% vector. Use FERROR to determine the nature of the error.
%
% MATLAB reads characters using the encoding scheme associated with the file. See
% FOPEN for more information.
%
% FGETL is intended for use with files that contain newline characters. Given a
% file with no newline characters, FGETL may take a long time to execute.
%
% Example
% fid=fopen('fgetl.m');
% while 1
% tline = fgetl(fid);
% if ~ischar(tline), break, end
% disp(tline)
% end
% fclose(fid);
%
% See also FGETS, FOPEN, FERROR.
% Copyright 1984-2016 The MathWorks, Inc.
narginchk(1,1)
[tline,lt] = fgets(fid);
tline = tline(1:end-length(lt));
if isempty(tline)
tline = '';
end
end
|