File operations‎ > ‎

Files: read & write

Read line by line from a text file


fid = fopen('myfile.txt', 'r');
  while ~feof(fid) % while not end-of-file
    fileline = fgets(fid); % read line by line
    ... % do something with each file line
  end
fclose(fid);


% example: search string "www" in each line of a text file
fid = fopen('myfile.txt', 'r');
  while ~feof(fid) % while not end-of-file
    fileline = fgets(fid); % read line by line

    fileline = strrep(fileline,sprintf('\n'),''); % remove newline character
    if ~isempty(strfind(fileline,'www')) % search string "www" in line
      disp('Found string "www" in line')
      disp(fileline)
    end

  end
fclose(fid);


Read complete text-file

mytext = fileread('mytext.txt');


check for newline character \n
strcmp(tline(end),sprintf('\n'))
remove newline character
strrep(tline,sprintf('\n'),'')


Read .csv files

mydata = readtable('mydata.csv')

mydata = readtable('mydata.csv','Format','%s%s%u%f%f%s')


% check column titles
mydata.Properties.VariableNames
    {'SampleID'}    {'Treatment'}    {'Time'}

% get second column of 'Treatment'
 x = mydata.Treatment % using column name
 
 id = find(ismember(mydata.Properties.VariableNames,'Treatment'))
    
2
 x = mydata(:,id); % using column index  id=2
 
x = mydata(:,2);   
  
% convert table to cell array
table2cell(mydata)



Subpages (1): fprintf