필터 지우기
필터 지우기

use fprintf to write to a new file

조회 수: 2 (최근 30일)
ERC
ERC 2013년 7월 24일
How do I write the data of one file ('source.dat') to another ('result.dat') using fprintf?
I tried,
fid=fopen('source.dat')
%I then manipulate the data of fid to my liking
result=fopen('result.dat','w')
fprinf(fid, desired format here)
Why am I getting an out-of-range error?
  댓글 수: 1
dpb
dpb 2013년 7월 24일
Need the actual code and the error directly instead of trying to tell us what it was...that'll include --- oh, I see it if what you actually did is identically what you posted...see answers.

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

채택된 답변

dpb
dpb 2013년 7월 24일
편집: dpb 2013년 7월 24일
...first I opened my source file via
fid=fopen('source.dat')
data=fscanf(fid, ... % get the data
fid=fclose(fid); % done w/ that file...
data=sqr(data); % do something to it
fid=fopen('results.dat','w'); % a new output file
fprintf(fid, fmt, data); % write it out
fid=fclose(fid); % close it now, too...
If you need to read and write to two (or more) files simultaneously, you must keep unique variables for them--fid1 and fid2 are popular as are things like fhi and fho (file handle in/out). If you ever do something like
fid=fopen('source.dat');
...
fid=fopen('output.dat','w');
you've just trashed the handle to source.dat and can no longer get to it--it's in limbo as it's open but your program has no valid way to communicate with it and you can't even close it cleanly other than by brute force hammer of
fclose('all')
or when Matlab itself finally closes and releases open handles.
doc fopen % and friends

추가 답변 (1개)

dpb
dpb 2013년 7월 24일
fid=fopen('source.dat')
% do some stuff to the (presumed read but unshown) data from 'source.dat'
result=fopen('result.dat','w')
fprinf(fid, desired format here)
fid is still the handle for 'source.dat' or is invalid if you have done an
fclose(fid)
OTOMH I don't recall what that error message is, would think it would be invalid handle or somesuch, however, not some out-of-range error.
The handle to 'result.dat' is the variable result as you've written it above so the print statement (Fortran syntax :) )/fprintf call should be
fprintf(result, fmt, data)
NB: there's no data in the call above to be written.
But, while those are problems, w/o the actual code and specific error can't see w/ the cloudy crystal ball what actually was the cause of the specific error or what it means.
  댓글 수: 1
ERC
ERC 2013년 7월 24일
I am still a little confused. Let me re-phrase my question:
So, first I opened my source file via
fid=fopen('source.dat')
How do I print the data in fid to a new file via fprintf?
Thanks.

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

카테고리

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

태그

제품

Community Treasure Hunt

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

Start Hunting!

Translated by