Why does fopen fail to find a file?

I'm using fopen within a function. The name of the file to be opened is passed in the function argument, so it looks like:
function [x y z] = myfun(finp)
...
[fid msg] = fopen(finp,'rt')
The file exists, but I get the 'No such file or directory' message. However, if I just enter fopen(finp,'rt') at the command line (after having run the main code, so finp is defined exactly as passed to the function), I get no error and a positive fid value.
The file itself is in a remote directory, eg ~/Dir1/Dir2/file. If, inside the function, I cd to Dir1, then fopen('Dir2/file','rt'), it works. However, I'd rather not have to do this if possible.
Any suggestions?

Answers (3)

Of course you have to define the folder in which the file is found, if this is not the current folder.
finp = fullfile('~/Dir1/Dir2/', file);
[x,y,z] = myfun(finp)
There is no other way, because different folders can contain files with the same name. To solve such ambiguities, the folder is required to define the path to the file uniquely.

1 Comment

This isn't the problem; finp contains the full pathname of the file. When I run fopen(finp,'rt') successfully from the command line, I'm doing so in the same (remote) working directory as the function that generates the error works in.

Sign in to comment.

You have to specify the folder and the filename, for example
folder='E:\matlab'
file='yourfilename'
finp=fullfile(folder,file)
[x y z] = myfun(finp)

2 Comments

Please see the comment that I've added to the first answer.
Post your function and how your are calling it

Sign in to comment.

Walter Roberson
Walter Roberson on 30 Aug 2013
Are you using the '~' as part of the string you are passing in? ~ is a shell-level shortcut, not an operating-system shortcut, so routines such as fopen() are allowed to not understand it (or to understand it inconsistently) unless they are documented to know about it.

3 Comments

I was, but I've now tried with the absolute pathname and found the same behaviour. The key difference between working/not working appears to be whether fopen is called from command line (or a script), or from within a function.
To check: you have displayed the filename and current directory just before the fopen() in each case and verified them to be the same ?
@Will: I do not believe that such a magic behavior is the reason for the problems. Either there is a typo or your program performs some important steps you did not explain yet, e.g. logging on to an external server or things like that.
What does this mean exactly: "I'm doing so in the same (remote) working directory as the function that generates the error works in."?

Sign in to comment.

Categories

Products

Tags

Asked:

on 30 Aug 2013

Community Treasure Hunt

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

Start Hunting!