Making a directory and adding it to the path

23 views (last 30 days)
Hello Community,
I am trying to create a new folder, named by user input and immediately have that folder added to the path. Currently, I am achieving this by two separate lines of code:
mkdir(input('Enter new folder name: ', 's'))
addpath(input('Enter Filename to be added to the path: \n', 's'))
but this is clunky as I have to manually enter the same information twice. I have tried this:
mkdir(genpath(input('Enter new folder name: ', 's')))
(also tried with addpath replacing genpath) but this doesn't work and generates the error:
Warning: An empty directory name was given. No directory will be created.
This syntax may not be supported in future releases.
So any thoughts on how I can combine the two commands ie to create a new folder and immediately add it and subfolders to the filepath?
Regards,
10B.

Accepted Answer

Guillaume
Guillaume on 28 Sep 2015
This is indeed very clunky. You seem to be allergic to variables, they're useful for storing information from one line to the next :)
while true
newfolder = input('Enter new folder name: ', 's');
[status, message] = mkdir(newfolder);
if ~status
sprintf('Failed to create folder because %s\n', message);
else
break; %get out of while loop
end
end
addpath(fullfile(pwd, newfolder)); %current folder is returned by pwd. Combined with newfolder gives full path.
Also note that I've added some error handling code, which you should always have when handling user input and / or filesystem. The user may enter invalid name, the folder may not be created due to permission, etc. It's always better to detect this than continue on your merry way.
  1 Comment
10B
10B on 28 Sep 2015
Excellent Guillaume!
This works perfectly. I think your observation is correct, although its not just my allergies to variables that causes problems - it seems that I may be allergic to Matlab altogether!

Sign in to comment.

More Answers (0)

Categories

Find more on Search Path in Help Center and File Exchange

Products

Community Treasure Hunt

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

Start Hunting!