使用 fopen 导入数据跳过行
Importing data skip lines with fopen
我尝试从导入 Matlab 的 .txt 文件中跳过第 5 行到文件末尾。
fidM = fopen('abc.txt', 'r');
for i = 5:150
fgetl(fidM);
end
buffer = fread(fidM, Inf) ;
fclose(fidM);
fidM = fopen('xyz.txt', 'w');
fwrite(fidM, buffer) ;
fclose(fidM) ;
上面的代码并没有以某种方式完成这项工作。有什么想法吗?
您的代码当前读取文件的前 146 行,丢弃它们,然后读取其余部分并将 that 写入文件。相反,如果您只想将 abc.txt
的前 5 行写入 xyz.txt
,则执行如下操作:
fid = fopen('abc.txt', 'r');
fout = fopen('xyz.txt', 'w');
for k = 1:5
fprintf(fout, '%s\r\n', fgetl(fid));
end
fclose(fid);
fclose(fout);
或者您可以删除循环并执行如下操作:
fid = fopen('abc.txt', 'r');
% Read in the first 5 lines
contents = textscan(fid, '%s', 5);
fclose(fid);
% Write these to a new file
fout = fopen('xyz.txt', 'w');
fprintf(fout, '%s\r\n', contents{1}{:});
fclose(fout);
我尝试从导入 Matlab 的 .txt 文件中跳过第 5 行到文件末尾。
fidM = fopen('abc.txt', 'r');
for i = 5:150
fgetl(fidM);
end
buffer = fread(fidM, Inf) ;
fclose(fidM);
fidM = fopen('xyz.txt', 'w');
fwrite(fidM, buffer) ;
fclose(fidM) ;
上面的代码并没有以某种方式完成这项工作。有什么想法吗?
您的代码当前读取文件的前 146 行,丢弃它们,然后读取其余部分并将 that 写入文件。相反,如果您只想将 abc.txt
的前 5 行写入 xyz.txt
,则执行如下操作:
fid = fopen('abc.txt', 'r');
fout = fopen('xyz.txt', 'w');
for k = 1:5
fprintf(fout, '%s\r\n', fgetl(fid));
end
fclose(fid);
fclose(fout);
或者您可以删除循环并执行如下操作:
fid = fopen('abc.txt', 'r');
% Read in the first 5 lines
contents = textscan(fid, '%s', 5);
fclose(fid);
% Write these to a new file
fout = fopen('xyz.txt', 'w');
fprintf(fout, '%s\r\n', contents{1}{:});
fclose(fout);