How to read data from a txt-file that is written by another program

6 views (last 30 days)
I'm creating a design optimization loop between Matlab and a simulation software. My Matlab code writes up a simulation and instructs the other program to solve it and write its results in a textfile (this part works well). To finish the loop i need a function to wait for the simulation to finish and then read the results that are in the text file. I have tried using a while-loop with with fopen, to wait for a file identifier that is not -1. But this loop continues forever, (unless i pause the process manually and restart it, then it suddenly finds it) even though the file is finished and closed by the other program in the meantime. I also have a regular expression that i know will match only with the last line of the result file so i tried a while loop that waited for a match. But since i need to use fileread to get the text in the file, and fileread uses fopen i have the same problem with it always returning a -1 file identifier. What is happening here, and does anyone have a solution?
function result=readresult(gen,n)
genstr = num2str(gen);
nstr = num2str(n,'%04d');
filename = ['OUTPUT_generation' genstr '.txt']; % Results filename e.g. OUTPUT_generation5.txt
fid= -1;
while fid==-1
pause(0.5);
fid = fopen(filename);
end
matchexp = ['\s+' genstr '\.' nstr '\s+']; % This expression matches with the last line in the results-file only
exp='(\d+\.\d+)\s*(\d+\.\d+)\s*(\d+\.\d+)\s*'; % This expression matches a set of results with tokens
result = zeros(n,3);
checkmatch = {};
while isempty(checkmatch) % wait for results file to be complete
text = fileread(filename);
checkmatch = regexp(text,matchexp,'once'); % check if results file is complete
end
result = regexp(text,exp,'tokens');
  7 Comments
Jóhann Egholm Vørmadal
Jóhann Egholm Vørmadal on 27 Feb 2020
Edited: Jóhann Egholm Vørmadal on 27 Feb 2020
Now i am initially calling the 'FileWatch' function instead of 'readresults'. But how can i now pass the 'results' variable back to the main function?
function listeners = FileWatch(pathToWatch, callback)
persistent Listeners;
% to check/clear the existing ones:
listeners = [];
switch pathToWatch
case 'clear'
Listeners = [];
return
case 'list'
listeners = Listeners;
return;
end
fileObj = System.IO.FileSystemWatcher(pathToWatch);
fileObj.EnableRaisingEvents = true;
changeListener = addlistener(fileObj, 'Changed', callback);
if isempty(Listeners)
Listeners = changeListener;
else
Listeners(end+1) = changeListener;
end
end
function handlefileevent(event,n,gen)
result = readresult(gen,n);
end

Sign in to comment.

Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!