Problem with creating .dat file

조회 수: 2 (최근 30일)
Giovanni Ponce
Giovanni Ponce 2022년 4월 17일
답변: Voss 2022년 4월 20일
Hello, I have a problem with this part of a code. could someone tell me if it has something to do with path of the file? I want to replace windcity.dat file and create my own .dat file for MATLAB. I using MAC and I tried (text editor>make plain text>and save as UTF-8) but I still get .txt at the end. I want to create an import file of my owm with .dat so I can output values.
% Open simulation output file and write header
if ( ~exist('theSimfile', 'var') )
simfile = 'Users/ponce/Desktop/folder 10/windcity.dat';
end
simfid = fopen( theSimfile, 'w' );
fprintf( simfid, ['#state1\tstate2\tstate3\tstate4\tstate5\n', ...
'original1\toriginal2\toriginal3\toriginal4\toriginal5\toriginal6\n', ...
'error1\terror2\terror3\terro4\n'] );
It is giving me this error:
Error using fprintf
Invalid file identifier. Use fopen to generate a valid file identifier.
Error in windbess (line 77)
fprintf(simfid, ['#state1\tstate2\tstate3\tstate4\tstate5\n', ...
'original1\toriginal2\toriginal3\toriginal4\toriginal5\toriginal6\n', ...
'error1\terror2\terror3\terro4\n'] );

답변 (1개)

Voss
Voss 2022년 4월 20일
You check if the variable theSimfile exists, and if it doesn't, you create a variable called simfile. Then you use theSimfile (which may not exist) in fopen, and simfile (which also may not exist) is unused.
I imagine that the intent in checking for the existence of a variable is to use a default file if it is not already specified, but probably the variable you create should be the one you just found not to exist (doesn't matter if it's called simfile or theSimfile). Then use that same variable in fopen.
Also, in case the file can't be opened for whatever reason, you can take the second output from fopen and throw it as an error.
(And don't forget to fclose the file.)
if ~exist('simfile','var')
simfile = 'Users/ponce/Desktop/folder 10/windcity.dat';
end
[simfid,simmsg] = fopen( simfile, 'w' );
if simfid == -1
error(simmsg);
end
fprintf( simfid, ['#state1\tstate2\tstate3\tstate4\tstate5\n', ...
'original1\toriginal2\toriginal3\toriginal4\toriginal5\toriginal6\n', ...
'error1\terror2\terror3\terro4\n'] );
% close the file when you are done writing!
fclose( simfid );

카테고리

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

제품


릴리스

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by