问题描述
我正在尝试在 C 程序中使用 system() 函数.
例如,我尝试使用 system() 函数在桌面上创建一个目录.
我的代码:
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;
}
当我运行此代码时,会创建一个目录,但不在我的桌面上.它是在我的项目目录中创建的.
为什么会这样?
我可以在 system() 函数中使用 cd 命令吗?如果没有,是否有可以与 system() 一起使用的 cd 命令的替代品?
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()?
我使用的是 Windows 操作系统.我正在尝试使用 C 程序中的 system() ,因为我使用 cmd 程序.
我知道我可以毫无问题地使用 WinAPI 创建目录.我不想使用 WinAPI,我的问题是如何使用 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().
推荐答案
更改后的目录仅在系统命令期间有效.该命令启动一个单独的程序,该程序从您的程序继承其当前目录,但是当该程序退出时,其当前目录随之消失.
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");
我还添加了 /D
开关,否则如果从不同的驱动器调用 CD 命令将不会更改驱动器号.
I also added the /D
switch, or the CD command would not change drive letter if it were called from a different drive.
但是,mkdir 完全能够接受完整路径,因此您可以简单地执行以下操作:
However, mkdir is perfectly capable of accepting a full path, so you could simply do:
system("mkdir C:\Users\USER\Desktop\test");
这篇关于C 程序中的 system("cd <path>")的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!