Why does the text file does not show me lines printed on next lines even when i used '\n' while printing the data in Matlab?

2 views (last 30 days)
I have a text file which i have created which has some data in it . I use '\n' to print each line on the next line using a for loop in the code .
I did this because i wanted to use 'textscan' later to create a cell array with this so that i can work on this file on Matlab.
BUt when i open the file in the directory , all the lines are printed one after the other , but in Matlab it shows the lines are well printed line after line .
I am attaching the text file i created and how it is showing on Matlab and when i open normally from the directory outisde Matlab.
Any help will be appreciated.I am attaching the code with it .Thank you.

Accepted Answer

Stephen23
Stephen23 on 15 Apr 2019
Edited: Stephen23 on 15 Apr 2019
You should fopen the file in TEXT mode:
fid = fopen(....'wt')
% ^ TEXT mode!
Or alternatively stop using retrograde Windows applications like Notepad.
"Why does the text file does not show me lines printed on next lines..."
Because you opened the file in BINARY mode which prints exactly the character that you requested (i.e. \n) but on Windows a new text line is indicated with two characters \r\n, which therefore your file does not contain and so your file is not shown on multiple lines. The simplest solution is to fopen the file in TEXT mode, which automatically makes this conversion for you.
This topic has been discussed thousands of times on this forum: search for "fopen newline".
  2 Comments
sachin narain
sachin narain on 15 Apr 2019
Thak you for the repsonse , but will the appending command work if i dont put '+a' because as i said while printing in the file , i am using a for,loop .
Thank youa again
Stephen23
Stephen23 on 15 Apr 2019
Edited: Stephen23 on 15 Apr 2019
You can use the TEXT mode while reading, writing, or appending: just add the t character, e.g. 'at+', exactly as the fopen help describes.

Sign in to comment.

More Answers (0)

Categories

Find more on Data Import and Export in Help Center and File Exchange

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!