How do I use fopen in a function?
9 ビュー (過去 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!