How to write into txt file

조회 수: 8 (최근 30일)
qingze
qingze 2013년 10월 11일
편집: Cedric 2013년 10월 11일
i want to write data into a txt file like
if true
% code
end
x = 0:.1:1;
A = [x; exp(x)];
fileID= fopen('exp.txt','w');
fprintf(fileID,'%6s %12s\n','x','exp(x)');
fprintf(fileID,'%6.2f %12.8f\n',A);
fclose(fileID);
But it always show that Error using fprintf Invalid file identifier. Use fopen to generate a valid file identifier.
Why i can't run this simple program!
Plz help.

답변 (2개)

Cedric
Cedric 2013년 10월 11일
편집: Cedric 2013년 10월 11일
If fopen cannot open the file, fileID is -1. Valid file IDs are generally above 2 for files that you open by yourself (1 being stdout and 2 stderr). So you should test that, e.g.
if fileID < 0
error('Could not open file!') ;
end
just after opening the file. Now there can be plenty of reasons for FOPEN to fail opening a file. One is that you don't have write access in the current folder. This is the case for example of the default MATLAB start folder ( MATLAB/RXXXXx/bin ). If it is the problem, just select a location where you have write access (e.g. My Documents/whatever).

sixwwwwww
sixwwwwww 2013년 10월 11일
Your code is working fine I checked. There is no problem with your code but it is windows permission problem. You should not save your file in default directory of MATLAB because it will not allow you create file there because of windows administration right problem. try to save file in some other drive like "E:\exp.txt" then it will work fine. Hope it will help you.

카테고리

Help CenterFile Exchange에서 Low-Level File I/O에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by