classdef (Abstract) FileExtractor < handle % Extract the variables defined in a .txt file. % % Example: % given an example.txt file wich contains only one line: % % foo = 42 % % running: % % test = FileExtractor.getVariableFromTextFile('foo','example.txt'); % % will attribute the value 42 to the variable 'test'. The same result % that would have been given by running: % % test = 42; properties (Abstract, Constant) filename end methods (Static) function output = getVariableFromTextFile(variableName,filename) output = []; assert(ischar(filename),'filename must be a char array') assert(ischar(variableName),'variableName must be a char array') assert( (exist(filename,'file') == 2),'File %s doesn''t exist',filename); fid = fopen(filename,'r'); while and(isempty(output), not(feof(fid))) line = fgetl(fid); variableFound = extractAfter(line,[variableName ' = ']); if not(isempty(variableFound)) eval(['output = ' variableFound ';']); end end assert(not(isempty(output)),'%s has not been found in %s',variableName,filename); fclose(fid); end end end