gyeox29ns
gyeox29ns

Reputation: 101

MATLAB simultaneous read and write the same file

I want to read and write the same file simultaneously. Here is a simplified code:

clc;
close all;
clearvars;

fd = fopen ('abcd.txt','r+'); %opening file abcd.txt given below


    while ~feof(fd)
        nline = fgetl(fd);
        find1 = strfind(nline,'abcd'); %searching for matching string
        chk1 = isempty(find1);
                if(chk1==0) 
                    write = '0000'; %in this case, matching pattern found
                    % then replace that line by 0000 
                    fprintf(fd,'%s \n',write);
                else 
                    continue;
                end


    end

File abcd.txt

abcde
abcd23
abcd2
abcd355
abcd65

I want to find text abcd in string of each line and replace the entire line by 0000. However, there is no change in the text file abcd.txt. The program doesn't write anything in the text file.

Someone can say read each line and write a separate text file line by line. However, there is a problem in this approach. In the original problem, instead of finding matching text `abcd, there is array of string with thousands of elements. In that case, I want to read the file, parse the file for find matching string, replace string as per condition, go to next iteration to search next matching string and so on. So in this approach, line by line reading original file and simultaneously writing another file does not work.

Another approach can be reading the entire file in memory, replacing the string and iterate. But I am not very sure how will it work. Another issue is memory usage.

Any comments?

Upvotes: 0

Views: 752

Answers (1)

Daniel
Daniel

Reputation: 36710

What you are attempting to do is not possible in a efficient way. Replacing abcde with 0000, which should be done for the first line, would require all remaining text forward because you remove one char.

Instead solve this reading one file and write to a second, then remove the original file and rename the new one.

Upvotes: 1

Related Questions