How do I use fopen in a function?
8 views (last 30 days)
Show older comments
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 Comments
jgg
on 22 Dec 2015
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
on 22 Dec 2015
or use:
which fopen in openclose
and avoid altering your code.
Answers (2)
Zachariah Norman
on 22 Dec 2015
1 Comment
jgg
on 22 Dec 2015
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
on 22 Dec 2015
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 Comments
See Also
Categories
Find more on Workspace Variables and MAT Files in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!