Why does the "dos" command not work as expected when using "cd" to switch directories?

9 views (last 30 days)
The "dos" command does not work as expected for switching directories with the "cd" command. 
>> [status, cmdout] = dos('cd C:\') cmdout = 0×0 empty char array
However, the "dos" command works for different operations like "dir" fine.
>> [status, cmdout] = dos('dir') cmdout = ' Volume in drive C is Windows Volume Serial Number is 6405-C0AD Directory of C:\Users\..\...\...\... 12/26/2024 04:35 PM <DIR> . 12/30/2024 02:49 PM <DIR> ..
Why does the "dos" command work with "dir" but not with "cd"?

Accepted Answer

MathWorks Support Team
MathWorks Support Team on 11 Apr 2025
Edited: MathWorks Support Team on 5 Apr 2025
The behavior you are observing is expected. When you use the "dos" command to execute a command like "cd", it runs in a separate command shell instance. This means that any directory changes made using "cd" within that shell do not affect the MATLAB environment itself. Essentially, each "dos" command operates in its own isolated shell session.
For changing the current working directory within MATLAB, you should use MATLAB's built-in "cd" function. Here’s how you can do it:
cd('C:\path\to\your\directory');
This command will change the directory for the MATLAB session, allowing any subsequent file operations to occur in the new directory.
However, you can execute command-line operations like listing directory contents using "dos", which does not affect MATLAB's current directory, like "dir":
[status, cmdout] = dos('dir'); disp(cmdout);

More Answers (0)

Categories

Find more on File Operations in Help Center and File Exchange

Products


Release

R2017b

Community Treasure Hunt

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

Start Hunting!