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'),'')