changing the directory from inside a c program und

2020-02-01 19:00发布

I have a problem where I have to run a command prompt command from inside a C program. Here is what I did

#include<stdio.h>
#include<stdlib.h>


int main(){



system("cd \Users");
system("Dir");

}

The problem is I want to cd into Users first and then execute the command Dir where as currently the program outputs that it cant find the path specified and the Dir is executed in the parent process directory i-e where the program source file is located.

The actual task I want to do is just want to run a java file from a particular directory from inside a C program. that java file is in C:\Users\Abdullah\pro . My C program's parent directory is C:\Users\Cprog. Please advise on how may I do this

5条回答
Animai°情兽
2楼-- · 2020-02-01 19:26

Your program has some incorrect assumptions. First of all, "cd" and "dir" are not programs, but commands built into the shell, cmd.exe. Second, I suspect you don't need to change the current directory at all.

Either way, since this is a Windows system, I would look at an example on how to start a program with CreateProcess().

For changing the current directory, check out the lpCurrentDirectory parameter of the CreateProcess() call.

查看更多
够拽才男人
3楼-- · 2020-02-01 19:40

This should work:

system("dir Users\\whatEverNextFolder > test.txt");
查看更多
走好不送
4楼-- · 2020-02-01 19:42

system() starts a new process. This new process changes its current directory, then ends. The current directory of your program's process does not change.

You want chdir() (or _chdir()).

查看更多
一纸荒年 Trace。
5楼-- · 2020-02-01 19:44

For Windows only, there is also this SetCurrentDirectory() function.

查看更多
Anthone
6楼-- · 2020-02-01 19:49

'cd' is NOT a separate executable which you are trying to execute. Normally 'cd' is a shell/command's built-in command. You can NOT execute 'cd' with 'system()' and expect to make it work accordingly in your program. You will have to use 'chdir()' function (or system call) if you want the directory change to be performed inside your program. Consult the manual page for 'chdir()'.

查看更多
登录 后发表回答