Making a directory and adding it to the path

15 次查看(过去 30 天)
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.

采纳的回答

Guillaume
Guillaume 2015-9-28
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 个评论
10B
10B 2015-9-28
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!

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Search Path 的更多信息

产品

Community Treasure Hunt

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

Start Hunting!

Translated by