在C程序系统(QUOT; CD<路径>&QUOT) [英] system("cd <path>") in a C program

查看:236
本文介绍了在C程序系统(QUOT; CD<路径>&QUOT)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

结果
我试图使用系统()函数的C程序。结果
例如,我想我的桌面上创建一个目录,使用system()函数结果我的code:结果


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;
}

当我运行这个code,A目录中创建的,但不是我的桌面上。它在我的项目目录中创建。结果
为什么会出现这种情况?结果
我可以在系统中()函数使用cd命令?如果没有,是否有更换的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操作系统。我想因为我用CMD程序从一个C程序中使用的系统()。结果
我知道我可以创建一个使用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程序系统(QUOT; CD&LT;路径&GT;&QUOT)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆