MATLAB: How to read n first lines of a txt file and keep the format when writing the read data to the new (another) text file

read datatextscanwrite data

Hi MATLAB folks,
I have a long .txt file which each line of that has its own specific format, e.g.
contents of a sample text file
created on Sept. 21, 2012
no. day month year
1 Sat Jan 2012
2 Mon Sept 2001
Now, I am looking for a way to read its, let say 4 lines, and keep the format of these lines when I am writing this data into other text file so that I end up with:
contents of a sample text file
created on Sept. 21, 2012
no. day month year
in my new .txt file.
Is there any suggestion?
Many thanks in advance, -V

Best Answer

To read into a cell array, line by line:
fid = fopen(your_filename,'r');
numLines = 4;
your_text = cell(numLines,1);
for ii = 1:numLines
your_text(ii) = {fgetl(fid)};
end
fclose(fid);
And now to save:
fid = fopen('your_file.txt','w');
for ii = 1:numLines
fprintf(fid,'%s\n',your_text{ii})
end
fclose(fis)
your_first_value = fscanf(fid,'%d',1);
fclose(fid);
Note that the return of carriage will be '\r\n' in Windows instead of just '\n'.