fprintf don't print newline character?

8 次查看(过去 30 天)
function pushbutton1_Callback(hObject, eventdata, handles)
outfile = fopen('E:\\out.txt','a');
inputstr = get(handles.txtbox_input,'String');
fprintf(outfile,'%c %s \n',13,inputstr);
fclose(outfile);
Each time I press the push button, I want it to write on a separate line. But It just don't do that. Bot \n and printing the ascii character 13 don't work.
Do you know what I should do?
  1 个评论
Fangjun Jiang
Fangjun Jiang 2011-5-20
What is the path of your text file? Is it mapping to a drive in a UNIX system. Your code looks fine.

请先登录,再进行评论。

采纳的回答

Jan
Jan 2011-5-20
This works fine for me:
File = fullfile(tempdir, 'TestFile.txt');
outfile = fopen(File, 'a');
inputstr = datestr(now, 0);
fprintf(outfile, '%s\n', inputstr);
fclose(outfile);
Does it work for ou? What is the difference to your case? Is inputstr a string or a cell string? You explain, that it "does not work" - but what is happening instead? Do you open the file with the Windows Editor, which is so dull, that it cannot interprete CHAR(10) as line break? Use WordPad or Matlab's editor...

更多回答(2 个)

Titus Edelhofer
Titus Edelhofer 2011-5-20
Hi,
"E:\\" looks like windows: you should open the file as a text file:
outfile = fopen('E:\\out.txt', 'at');
Note the "t" in the second argument. Then it should work just with
fprintf(outfile, '%s\n', 'Hello MATLAB!');
Titus
  1 个评论
Jan
Jan 2011-5-20
The text mode influences the translation of '\n': In text mode and on Windows, '\n' is written as CHAR([13,10]). All modern editors, even the editor of Matlab 5.3, accept CHAR(10) as line break also. Only the Windows Editor fails to interprete this.
The text mode has some other drawbacks (under Windows, under linux it is simply no difference): A CHAR(27) is interpreted as end-of-file, CHAR(8) is interpreted as BackSpace, CHAR([13,10]) is counted as 1 characters such that FSEEK(FID,0,1), FTELL(FID) can reply unexpected results. There are so many pitfalls in the text mode, that I recommend beginners to avoid it.

请先登录,再进行评论。


Rajendra
Rajendra 2011-5-20
Thanks everybody for help Yeah, that was an especial issue with the windows notepad, as most of you had said. doing matlab suggested \n\r would put it in new line. (found after some search)
I liked this question You explain, that it "does not work" - but what is happening instead? The answer: it just gets printed on the same line contiguously. But I thought the answer was obvious.
Cheers.
  1 个评论
Jan
Jan 2011-5-20
Even the obvious behaviour is usually worth to explain here: The less thinking is needed to create an answer, the more likely do the answer match the real problem instead of my fantasies about what the problem should be.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Entering Commands 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by