在不使用单元格的情况下替换文本文件中的N行

时间:2014-06-02 15:29:10

标签: matlab file fopen

有没有更快的方法在不使用单元格的情况下用另一个文件替换第三行文件?

我已经使用过这段代码,但它会减慢我的程序,特别是我的txt文件由超过1000行组成

% Read txt into cell A
    fid7 = fopen([handles.filenameproba],'r');
    i = 1;
    tline = fgetl(fid7);
    A{i} = tline;
    while ischar(tline)
        i = i+1;
        tline = fgetl(fid7);
        A{i} = tline;
    end
    fclose(fid7);
    % Change cell A
    newval =...

    A{3} = sprintf('StartExperiment:%s',num2str(newval);
    % Write cell A into txt
    fid7 = fopen([handles.filenameproba], 'w');
    for i = 1:numel(A)
        if A{i+1} == -1
            fprintf(fid7,'%s', A{i});
            break
        else
            fprintf(fid7,'%s\n', A{i});
        end
    end
  fclose(fid7);

谢谢!

2 个答案:

答案 0 :(得分:0)

如果您的主要考虑因素,请尝试使用此 importdata 方法,看看它是否更快 -

f=importdata(handles.filenameproba,'')
f(3)={sprintf('StartExperiment:%s',num2str(newval))}

%%// Save the modified text file
fid1 = fopen(handles.filenameproba,'w');
for k = 1:numel(f)
    fprintf(fid1,'%s\n',f{k});
end
fclose(fid1);

答案 1 :(得分:0)

细胞不是你的问题。你的问题是一次读写一行。此外,您将在每次迭代时重新调整单元格数组的大小。

对于以下问题,我创建了一个包含10000行的测试文件。

fileId = fopen('test.txt', 'w');
for i = 1:10000
    fprintf(fileId, 'This is the %dth line.\n', i);
end
fclose(fileId);

我正在调用您的方法ranellMethod

>> timeit(@ranellMethod)

ans =

    0.5160

更好的方法是限制您必须执行的读/写操作次数。假设您的文件足够小,您可以立即将整个内容读入内存。执行您的操作,并立即写下所有内容。

function entireFileMethod()
    fileName = 'test.txt';
    fileId = fopen(fileName, 'r');
    try
        text = fread(fileId, '*char')'; %'
    catch Me
        fclose(fileId);
        Me.rethrow();
    end
    fclose(fileId);
    newLineInds = find(text == char(10));
    newLine = sprintf('This is the new line. %1.*f', randi(10), rand);
    newText = [text(1:newLineInds(2)), newLine, text(newLineInds(3):end)];
    fileId = fopen(fileName, 'w');
    try
        fprintf(fileId, '%s', newText);
    catch Me
        fclose(fileId);
        Me.rethrow();
    end
    fclose(fileId);
end

该函数有一个读操作和一个写操作:

>> timeit(@entireFileMethod)

ans =

    0.0043

有关MATLAB中文件IO的更多详细信息,请参阅Fastest Matlab file reading?

相关问题