Trouble with fprintf,fopen and fscanf

2 views (last 30 days)
Hello, I see there are quite a few questions for 'fprintf'. I went through a lot of them but could not resolve my issue by myself. I need help for working this out. I have a set of names. I want to write down these names in a .txt file. If the names are repeating in the set, I want to write them only once to my .txt file.
Presently, the names are being written in a single line to my .txt file. I want them one below the other. (I am using \n\r for my Windows machine).
This writing process occurs multiple times in my actual code. So I want to create the text file only the first time my for loop runs. The code looks as follows:
people = {'demi','britney','demi','michael'};
%If file does not exist, create a file
if exist('singer.txt') == 0;
fid = fopen('singer.txt','wt');
fclose(fid);
end
for i = 1:length(people)
%Open the created file and read its contents into variable 'content'
fid = fopen('singer.txt','r');
content = fscanf(fid,'%s');
fclose(fid);
if isempty(strmatch(people{i},content)) == 1 %if 'content' already has a name in it that matches with current name(people{i}), do nothing
%convert people name from cell to char - because fprintf works
%only with characters
people_char = char(people{i});
people_use = people_char(1,:);
fid = fopen('singer.txt','a');
fprintf(fid,'%s\n\r',people_use);%write to new lines everytime
fclose(fid);
end
end
Please let me know how to make this work.
Thank you very much.
Ranjit

Accepted Answer

Walter Roberson
Walter Roberson on 23 Dec 2012
If I recall correctly, MS Windows uses \r\n rather than \n\r . But you can avoid that whole question by use 'rt' when you read, and 'at' when you append, and use only \n to indicate newline; the \n will automatically be translated into the appropriate two-character sequence for MS Windows.
  1 Comment
ranjit
ranjit on 24 Dec 2012
Thanks a lot. It was driving me nuts to figure out this one!

Sign in to comment.

More Answers (0)

Categories

Find more on Entering Commands 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!