How can I fopen files in different directory

How can I fopen files that are in a different directory than current directory, fopen always returns -1.

 Accepted Answer

Do NOT follow advice of just adding more directories to the Search Path: this just pointlessly slows MATLAB down (MATLAB has to keep track of all of the files in all folders on the Search Path). In general you should NOT add data folders to the search path, because all MATLAB functions that import/export data files accept relative or absolute filenames, and this is much more efficient than bloating the Search Path. For example:
D = 'E:\mails spamnon\non spam';
S = dir(fullfile(D,'*.*'));
for k = 1:numel(S)
F = fullfile(D,S(k).name);
fid = fopen(F);
...
fclose(fid);
end

More Answers (1)

Hello,
Please add the path containing the file you want to open to the MATLAB search path.
Regards,
stozaki

3 Comments

I have a list of emails in .txt format files I have to read these files first one by one, I have looped through these. The fopen(file) is always returning -1. Please suggest a solution. My working directory is different.
Files=dir('E:\mails spamnon\non spam')
for k=1:length(Files)
file=Files(k).name
fopen(file)
end
Please try following command.
addpath(genpath('E:\mails spamnon\non spam'))

Sign in to comment.

Categories

Asked:

on 25 Jan 2020

Commented:

on 25 Jan 2020

Community Treasure Hunt

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

Start Hunting!