如果您的标题以特定字符为前缀,那么您可以使用textscan's 'CommentStyle'NV-pair 忽略它们:
具有以下内容test.txt:
# A header line
1 2
3 4
5 6
我们可以用:
fID = fopen("test.txt", "r");
M = textscan(fID, "%f", "CommentStyle", "#");
M = reshape(M{:}, 2, []).';
fclose(fID)
这给了我们:
>> M
M =
1 2
3 4
5 6
或者,如果您想坚持使用fscanf,可以检查文件的第一行fgetl并使用frewind,如有必要(因为fgetl移动文件指针),如果没有标题,则返回文件的开头。
例如:
fID = fopen("test.txt", "r");
% Test for header
tline = fgetl(fID); % Moves file pointer to next line
commentchar = "#";
if strcmp(tline(1), commentchar)
% Header present, read from line 2
M = fscanf(fID, "%f", [2, inf]).';
else
% Header present, rewind to beginning of file & read as before
frewind(fID);
M = fscanf(fID, "%f", [2, inf]).';
end
fclose(fID);
这给出了与上面相同的结果。如果标题行的数量不是恒定的,您可以使用andftell循环跳过过去的标题,但此时您可能会使事情变得比此应用程序真正需要的更复杂。fseekwhile