Never mind. I split the read and write parts to two separate functions, used a try-catch block with fclose('all') in both functions, and now everything works fine. The "dummy_file.txt" file can be edited, either manually or by other programs, with no problem, while the matlab code is continuously monitoring the content of the file. Hope it helps whoever is reading this!
write_to_dummy('dummy_file.txt', '0');
dummy = read_dummy('dummy_file.txt');
while dummy == '0'
pause(1)
dummy = read_dummy('dummy_file.txt')
%Wait until another program performs and finishes calculation and rewrites the "0" to "1"
end
function write_to_dummy(fileName, varargin)
try
fid = fopen(fileName,'w+t');
fprintf(fid,varargin{1});
fclose('all');
catch me
fclose('all');
disp('error while writing to the dummy_file.txt')
rethrow(me);
end
end
function dummy = read_dummy(fileName)
try
fid = fopen(fileName,'rt');
fseek(fid,0,-1); %go to beginning of the file
dummy = fgetl(fid);
fclose('all');
catch me
fclose('all');
disp('error while reading the dummy_file.txt')
rethrow(me);
end
end