file handling between different functions.

조회 수: 4 (최근 30일)
angus wu
angus wu 2011년 6월 14일
[EDIT: 20110614 13:44 CDT - reformat - WDR]
there are three functions A, B, C
A - main function creates a file with the prompted filename
fid = fopen('filename');
call function B
close all files with fclose('all');
B - process some data and printf out to file speicified with fid
fprintf(fid, '%e, ...\n', var);
call function C
C - process some data and printf out to file speicified with fid
fprintf(fid, '%e, ...\n', var);
end
fid is declared in all three functions A, B, C as global by
function A
global fid;
fid = fopen('filename');
..
call function B;
..
fclose('all');
function B
global fid;
process data
fprintf(fid, '%e, ...\n', var);
..
call function C
...
function C
global fid;
process data
fprintf(fid, '%e, ...\n', var);
..
but it does not work at all. is there anyway to make the file be accessaible by the all three functions?

답변 (3개)

Walter Roberson
Walter Roberson 2011년 6월 14일
That looks like it should work. What value do you see for fid in function B after the "global" line has been executed?

Fangjun Jiang
Fangjun Jiang 2011년 6월 14일
It works for me. Try it yourself.
function a=FunA
global fid;
a=0;
fid=fopen('test.txt','wt');
fprintf(fid,'function a\n');
FunB;
fclose('all');
end
function b=FunB
global fid;
b=0;
fprintf(fid,'function b\n');
FunC;
end
function c=FunC
c=0;
global fid;
fprintf(fid,'function c\n');
end

Chirag Gupta
Chirag Gupta 2011년 6월 14일
Just pass the fid from function to function.
function A(filename)
fid = fopen(filename,'w');
% call function B
B(fid,other params);
%...
function B(fid,other_params)
% use passed fid to fprintf
% call C and pass fid
C(fid,other_params
%...
function C(fid,...)
%...
Is there any reason why you want the fid as global?

카테고리

Help CenterFile Exchange에서 Data Import and Analysis에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by