1

我正在打开一个文件,使用 读取第一行fgets,使用regexp来测试文件的格式,如果文件是所需的格式,我使用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,但c仅等于最后 4 行:

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

有没有办法防止fgets删除第一行?还是我应该使用的其他功能?

4

1 回答 1

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

它当然不是最优雅的解决方案,但它很健壮且易于硬塞到您现有的代码中。

于 2013-06-21T22:45:27.023 回答