error when using fprintf

조회 수: 1 (최근 30일)
Richard
Richard 2012년 2월 20일
can anyone tell me where I'm going wrong here.
clear all
data = rand(365,1);
filename = fullfile('file','test.txt');
fid = fopen(filename,'w');
fprintf(fid,'%s\n',data);
fclose(fid)
I'm trying to save a column vector into a .txt file but get the error:
Error using fprintf
Invalid file identifier. Use fopen to generate a valid file identifier.
The error says that I need to use fopen but I have used it so I'm not sure why an error occurs!

답변 (2개)

Walter Roberson
Walter Roberson 2012년 2월 20일
Your fopen() is failing, but you are not checking for that.
Your code is attempting to create a file named "test.txt" in a directory named "file" relative to the current directory. Is that your intention? Does the directory exist?
  댓글 수: 3
Walter Roberson
Walter Roberson 2012년 2월 20일
You may need to open with 'wt' rather than with 'w' . 'wt' is for text files, and 'w' is for binary files.
Richard
Richard 2012년 2월 20일
that works, thank you very much.

댓글을 달려면 로그인하십시오.


Image Analyst
Image Analyst 2012년 2월 20일
Try adding this line right before the fullfile() line
if ~exist('file', 'dir')
% The (badly named) folder called "file" does not exist.
% Create that folder.
mkdir('file');
end
Beyond that, you're opening a file not in text mode and then using a text format specifier (%s) to write out numerical data. What do you think that will do? Maybe you should use %f instead.

카테고리

Help CenterFile Exchange에서 File Operations에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by