Read text file line-by-line in deployed application
8 views (last 30 days)
Show older comments
MathWorks Support Team
on 9 May 2019
Edited: MathWorks Support Team
on 18 Mar 2020
I am trying to read a large TXT file in my deployed application, but I am encountering memory limitations. Therefore, I would like to read in the TXT file line by line, but the function 'fgetl' is not supported for C/C++ code generation with MATLAB Coder.
Is there any other way to read a TXT file line by line?
Accepted Answer
MathWorks Support Team
on 18 Mar 2020
Edited: MathWorks Support Team
on 18 Mar 2020
This can be achieved using the functions "fgets" or "fgetl". The code generation support for these functions was introduced in R2019b. See the documentation for additional details:
For C/C++ deployment of your MATLAB code in releases prior to R2019b, you will have to write your own implementation of this functionality.
One possible solution to read a TXT file line-by-line could be as follows:
function main
%#codegen
fid = fopen('myfile.txt');
lne = myfgetl(fid);
while ~isempty(lne)
fprintf(1,'%s',lne);
fprintf(1,'%s',sprintf('\n'));
lne = myfgetl(fid);
end
fclose(fid);
end
function line = myfgetl(fid)
line = '';
c = fread(fid,1,'char=>char');
while ~feof(fid) && ~strcmp(c, sprintf('\n'))
if ~strcmp(c,sprintf('\r'))
line = [line,c];
end
c = fread(fid,1,'char=>char');
end
end
0 Comments
More Answers (0)
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!