我正在打开一个文件,使用fgets
读取第一行,使用regexp
来测试文件的格式,如果文件是所需的格式,我使用{{ 1}}读取整个文件。
fscanf
不幸的是,如果我的文件内容如下:
fid = fopen('E:\Tick Data\Data Output\Differentformatfiles\AUU01.csv','rt');
% reads first line of file but seems to be deleting the line:
str = fgets(fid);
% test for pattern mm/dd/yyyy
if(regexp(str, '\d\d/\d\d/\d\d\d\d'))
c = fscanf(fid, '%d/%d/%d,%d:%d:%d,%f,%d,%*c');
20010701,08:29:30.000,95.00,29,E
20010702,08:29:30.000,95.00,68,E
20010703,08:29:30.000,95.00,5,E
20010704,08:29:30.000,95.00,40,E
20010705,08:29:30.000,95.00,72,E
将等于str
,但20010701,08:29:30.000,95.00,29,E
只会等于最后4行:
c
有没有办法阻止20010702,08:29:30.000,95.00,68,E
20010703,08:29:30.000,95.00,5,E
20010704,08:29:30.000,95.00,40,E
20010705,08:29:30.000,95.00,72,E
删除第一行?或者我应该使用的其他功能?
答案 0 :(得分:1)
它实际上没有删除它,它只是转移到下一行。您可以使用fpos
和fseek
的组合返回到该行的开头,但由于您已经将该行存储在str
中,我会添加两行:
if(regexp(str, '\d\d/\d\d/\d\d\d\d'))
c1 = sscanf(str, '%d/%d/%d,%d:%d:%d,%f,%d,%*c'); % scan the string
c2 = fscanf(fid, '%d/%d/%d,%d:%d:%d,%f,%d,%*c');
c = {c1;c2}; % concatenate the cells
它当然不是最优雅的解决方案,但它很强大且易于在现有代码中进行操作。