How do I use fopen in a function?
조회 수: 8 (최근 30일)
이전 댓글 표시
I'm trying to open and close files in functions. The overall goal is to be able to write structured data files that contain and arbitrary header followed by data. Right now I am stuck on the simplest step, opening a file in a function.
Below is the minimum length of code that I think should work, but generates an error.
function [] = openclose(fname)
ofile = fopen(fname)
fclose(ofile)
end
I thought this should just open and close the file whose filepath is in the chararray fname. Instead it generates the following error:
Error using openclose (line 2)
Not enough input arguments.
If I replace fname with a hardcoded string (such as 'file.txt') it works. I think there is something basic I am not understanding about matlab syntax here. Do I need to explicitly cast the variable type? What's going on?
댓글 수: 2
jgg
2015년 12월 22일
This code works for me! Do you have another function named fopen living in your directory somewhere?
Alternatively, you could insert keyboard into your function and drill down using debug mode to find out what fopen is causing problems.
Brendan Hamm
2015년 12월 22일
or use:
which fopen in openclose
and avoid altering your code.
답변 (2개)
Zachariah Norman
2015년 12월 22일
댓글 수: 1
jgg
2015년 12월 22일
You should accept your own answer! It's a clear resolution.
You can't really use multiple functions in a file: functions beyond the first are "private" to the first function in the file.
Steven Lord
2015년 12월 22일
In your question you wrote:
"I thought this should just open and close the file whose filepath is in the chararray fname."
MATLAB functions don't automatically pull data from their calling workspace with the same variable name as the variable used in its declaration. If you want something passed into the function as an input argument, you must call the function with the desired input.
So if you have a variable named fname in your workspace, you will need to pass that variable into your function.
fname = 'myfile.txt';
openclose(fname)
If you have a variable named z in your workspace that you want to be passed into the function:
z = 'abcde.txt';
openclose(z)
If you want to call the function with a plain old string, you can do that too:
openclose('xyzzy.txt')
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Workspace Variables and MAT Files에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!