strange behavior with fopen

I have a variable which is a string. When I call fopen with it, it returns -1. When I make the exact same call with fopen by evaluating the string variable, it opens correctly. THis is on a Linux system. Here is a sample of what I'm talking about using the command line:
K>> ischar(testdata.fullfn)
ans = 1
K>> testdata.fullfn
ans = '/home/data/blah.txt'
K>> fid = fopen(testdata.fullfn, 'r')
ans = -1 (open fails)
K>> fid = fopen ('/home/data/blah.txt', 'r')
ans = 3 (open succeeds)
Thus, the file is not open in some other app, the specified path and file exist, I have permission to read it ... but for some reason, fopen does not like the variable! Any ideas? Thanks in advance!

2 个评论

Call fopen with two output arguments and show us what the contents of the second output are when fopen returns -1.
and what does
strcmp(testdata.fullfn, '/home/data/blah.txt')
return?

请先登录,再进行评论。

回答(1 个)

There's an inconsistency here...
K>> testdata.fullfn
ans = '/home/data/blah.txt'
shows the single quotes around the content which indicates that the variable is a cell string but ischar then should've returned false instead.
To prove conjecture, try
fid = fopen(char(testdata.fullfn), 'r')
I'm guessing there's a context issue between the two cases above where there are different variables extant of the same name but in different scopes.
ADDENDUM
Or, possibly the variable is a character string but has the single quotes embedded in it if was constructed incorrectly...
>> test = '''/home/data/blah.txt''';
>> test
test =
'/home/data/blah.txt'
>> ischar(test)
ans =
1
>>
Produces all the symptoms consistently in that is character string, output "looks like" a cell string but fopen will fail because the filename won't match with the added quotes.

1 个评论

The last explanation matches the description perfectly:
>> str = '''blah.m'''
str = 'blah.m'
>> [fid,msg] = fopen(str,'rt')
fid =
-1
msg =
No such file or directory
>> new = eval(str);
>> [fid,msg] = fopen(new,'rt')
fid =
3
msg =
''

请先登录,再进行评论。

类别

帮助中心File Exchange 中查找有关 Large Files and Big Data 的更多信息

产品

Community Treasure Hunt

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

Start Hunting!

Translated by