1

最初我的文件看起来像:

1.4 2.0
4.2 2.1
5.1 1.2

列号是固定的,而行号因文件而异。以下代码可以读取这些文件:

fid = fopen("my_file.txt","r");
M = fscanf(fid,"%f",[2,inf]);

M是数据文件的转置。

现在我得到了几个新文件,其中可能有一个行标题,开头为#

# file description
1.0 2.0
1.5 2.2

保证 then header 占用不超过一行,并且总是以#.

我知道我可以逐行读取文件来处理标题。我想知道是否有任何方法可以对原始代码进行尽可能少的更改,以便新代码可以读取两种格式的文件。

textscanf函数似乎能够处理标题,但字段的参数Headerlines是固定数字。

4

1 回答 1

3

如果您的标题以特定字符为前缀,那么您可以使用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

于 2018-04-11T18:01:24.233 回答