Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
231 views
in Technique[技术] by (71.8m points)

windows - system("cd <path>") in a C program


I'm 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:

#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 happens?
Can I use the cd command in the system() function? If not, is there an replacement to the cd command that will work with system()?

I'm using Windows OS. I'm trying to use system() from a C program as I use cmd program.
I know that I can create the directory using WinAPI without any problem. I don't want to use WinAPI, my question is how can I make it work using system().

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The changed directory only lasts for the duration of the system command. The command starts a separate program, which inherits its current directory from your program, but when that program exits its current directory dies with it.

You can use && to join the commands together, and it will work:

system("cd /D C:\Users\USER\Desktop && mkdir test");

I also added the /D switch, or the CD command would not change drive letter if it were called from a different drive.

However, mkdir is perfectly capable of accepting a full path, so you could simply do:

system("mkdir C:\Users\USER\Desktop\test");

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...