How to read data from a txt-file that is written by another program
10 views (last 30 days)
Show older comments
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');
Answers (0)
See Also
Categories
Find more on Low-Level File I/O in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!