how to textscan to read all the lines in a file

matlab

Solution

Since you do not list your needs (are you reading a huge file?, many small files? is speed an issue? what do you really want to do?) I'm giving you the simplest possible answer:

You do this:

f = fopen('data.txt');             
g = textscan(f,'%s','delimiter','\n');
fclose(f);

remember to close after reading, because otherwise you won't be able to read again.

You can get the first line as g{1}{1}, the second as g{1}{2} and so on.

Here is the matlab documentation for textscan which gives a lot more details.

Problem

I am trying to read all the lines in a .m file with the following ``` file_content = textscan(fid, '%s', 'delimiter', '\n', 'whitespace', '') ``` but this just returns ``` file_content = {0x1 cell} ``` when actually my file has 224 line. so if i use ``` file_content = textscan(fid,'%s',224,'delimiter','\n') ``` i get all the lines ``` file_content = {224x1 cell} ``` what will be a more proper way to read all the data(mostly strings) in a .m file? thanks

Original source