gpt4 book ai didi

ios - 如何使用路径调用 cd 命令?

转载 作者:行者123 更新时间:2023-11-30 18:48:46 26 4
gpt4 key购买 nike

我想在我的工具中调用 cd 命令,但没有路径,因为它是内置命令。

我已成功使用 /bin/mkdir 调用 mkdir

cd 使用的路径是什么?

这是mkdir的代码:

pid_t pid;
int status;
const char *argv[] = {"mkdir", "Folder", NULL};
posix_spawn(&pid, "/bin/mkdir", NULL, NULL, (char* const*)argv, NULL);
waitpid(pid, &status, WEXITED);

最佳答案

这是更改当前进程目录的相当标准的方法。我已经删除了子进程的生成,这是不必要的:

#include <stdio.h>
#include <errno.h>
#include <unistd.h>
#include <sys/stat.h>
#include <limits.h>
#include <stdlib.h>

int main()
{
int status;
const char *argv[] = {"mkdir", "Folder", NULL};

status = mkdir(argv[1], S_IRWXU);
if (status != 0 && errno != EEXIST) {
perror("mkdir");
exit(1);
}

status = chdir(argv[1]);
if (status != 0) {
perror("chdir");
exit(1);
}

// Print current directory name
char buffer[PATH_MAX] = {0};
printf("%s\n", getcwd(buffer, PATH_MAX));

return 0;

}

错误处理和权限相当简单,您可能需要增强它们。

关于ios - 如何使用路径调用 cd 命令?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44653076/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com