How to write into txt file

4 ビュー (過去 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 Center および File ExchangeLow-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