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

标签 ios c bash unix terminal

我想在我的工具中调用 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/

相关文章:

bash - 如何使用 bash 执行任何编辑其文件(参数) "in place"的命令?

ios - GCM 始终为 iOS 设备返回 "NotRegistered"

c - 使用 strcpy 通过指针运算符将字符串复制到结构的成员

ios - 核心数据文件位于何处?

杀死 parent 后关闭文件子描述符?

c - 豪 pig 号用c程序

Bash:逐行读取文件并将每个段作为参数处理给其他程序

bash - 自动解密并运行加密的 bash 脚本而不将解密的文件保存到文件系统

ios - 用 swift 删除键盘

ios - 显示 UINavigationBar 不工作