System ("cd <path>") in a C program
I am trying to use the system () function in a C program. For example, I tried to create a directory on my desktop using the system () function.
My code is:
#include <stdio.h> #include <stdlib.h> int main(void) { system("cd c:\\Users\\USER\\Desktop"); system("mkdir test"); return 0; } When I run this code, a directory is created, but not on my desktop. It is created in my project directory.
Why is this happening?
Can I use the cd command in the system () function? If not, is there a replacement for the cd command that will work with system ()?
I am using windows. I am trying to use system () from a C program as I am using a cmd program.
I know that I can create a directory using WinAPI without any problems. I do not want to use WinAPI, my question is how can I make it work using system ().
The changed directory lasts only throughout the entire system command. The command launches a separate program that inherits its current directory from your program, but when this program leaves the current directory, it dies with it.
You can use && to combine teams together and it will work:
system("cd /DC:\\Users\\USER\\Desktop && mkdir test"); I also added the /D switch, or the CD command will not change the drive letter if it was called from another drive.
However, mkdir is quite capable of taking the full path, so you can simply do:
system("mkdir C:\\Users\\USER\\Desktop\\test"); When you say system("some shell command"); , the program launches a shell to run the command. The shell has its own idea of ββthe current directory, separate from your program. Shell the cd into the directory as you requested it, and then die, leaving your CWD process unaffected.
You can simply say _chdir("c:\\Users\\User\\Desktop"); to set the current directory before running the mkdir command. The shell that starts to run it then inherits your current program directory and makes the folder in the right place.
(In this case, you could say _mkdir("test") , and also refuse to use system unnecessarily. You should only use system when trying to do something that is worth running an external program / shell for.)