Code doesn't work with different path
7 views (last 30 days)
Show older comments
Hi, I have some code* which works well when I define the path to be my Dropbox (installed on the hard disk):
data_path = fullfile('/Users/me/Dropbox/folder/subfolder')
Now, I copy the 'subfolder' from above on a stick and specify the path as follows:
data_path = fullfile('/Volumes/Mystick/subfolder')
With the new path, I try to run the code* again. Now I get an error message. I have verified several times that the new path is correct. The piece of code below is part of a loop. When I ask Matlab how many files it finds in the loop, it finds more with the new path (even though I only copied the folder). This is why I suspect that there are some "hidden" files which provoke the error. Specifically, the error concerns
line= fgetl(f);
Error using fgets
Invalid file identifier. Use fopen to generate a valid file identifier.
Has anyone experienced a similar problem?
*This is the (relevant part of the) code - however, I don't think there is a problem with the code as such because it works perfectly with the first path.
f = fopen(filename_x);
% Read the first line and get the header line
line= fgetl(f);
% Split up the headers
headers = strsplit(line, ',');
% Read the rest of the data
data = textscan(f, '%d%d%f%f', 'Delimiter', ',');
% Reconstruct the data
out_x = [num2cell(data{1}) num2cell(data{2}) num2cell(data{3}) ...
num2cell(data{4})];
% Place the headers
out_x = [headers; out_x];
% Close the file
fclose(f);
0 Comments
Accepted Answer
Guillaume
on 6 Sep 2016
Actually, you have missed the important part of the code: how is filename_x obtained?
If you get an 'invalid file identifier', that means that there was a problem opening the file. Either it does not exist, or you don't have permission, or some other reason. From the information, you've given it's impossible for us to say what.
In any case, when dealing with user input or file system (things that are not under your control), it is always a good idea to check that what you're getting is indeed what you expect. In this case, always check that the file you're trying to open has indeed been opened. So:
f = fopen(filename_x);
if f == -1 %failed to open file
warning('failed to open %s', filename_x);
else
%... continue with processing file
%...
fclose(f);
end
Even better, would be to wrap the whole IO code inside a try ... catch block so that if a file disappear mid-processing (e.g. the usb drive is unplugged) you can cope with it.
More Answers (0)
See Also
Categories
Find more on Large Files and Big Data 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!