How to Differentiate between '\n' and CR/LF when reading in text files in MATLAB

22 vues (au cours des 30 derniers jours)
I am trying to read in a text file where each row contains a string. Some rows contain the character combination '\n' and '\r', and then all rows end with a CR and LF marker (I opened the file in Notepad++ to see this). For example:
First Name
Birthdate
Average\nLength
Avoid\rWater
...and so on.
The issue is that when I use textscan and set either '\n' or '\r' as the delimiter, MATLAB parses the incoming file at every '\n' or '\r' and CR or LF, where I need to only have actual carriage returns and line feeds break the line. Is there some sort of identifier I can use to differentiate a CR/LF from '\n' and '\r'?
fid=fopen('text.txt', 'r+');
full=textscan(fid, '%s', 'Delimiter', '\n') % I tried with '\r' as delimiter as well, and the result is the same
printFile=fopen('results.txt', 'at');
for i=1:length(full{1})
str=full{1}{i};
str=strrep(str, '\n', '$'); % I need to input a '$' as a manual delimiter in place of actual CR and LF.
% However this will replace both '\n' *and* CR/LF with '$'.
fprintf(printFile, '%s$', str);
end
fclose all;

Réponse acceptée

akazakov
akazakov le 20 Juil 2016
I've been sitting with this problem for a while, and the second I posted a question I figured it out :)
a=sprintf('\n') % a now equals a line feed
b=sprintf('\r') % b now equals a carriage return
Using these as delimiters directly solves my problem. So given my original sample code:
fid=fopen('text.txt', 'r+');
full=textscan(fid, '%s', 'Delimiter', sprintf('\r'));
fclose all;
% This reads in the text file, creating a new line at every carriage return
% and doing nothing when it sees a '\n' or '\r'

Plus de réponses (0)

Catégories

En savoir plus sur Characters and Strings dans Help Center et File Exchange

Produits

Community Treasure Hunt

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

Start Hunting!

Translated by