c - 如何实现 Unix 命令 "dirname"?

标签 c unix dirname

我不知道如何为这个命令编写代码。

我有一些东西但没有用。我认为是 exec 的问题。

有人可以让它工作吗?

我是这个领域的新手。

#include<sys/stat.h>
#include<libgen.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/types.h>
#include<dirent.h>
#include<stdio.h>

void showArgs(int argc, char *argv[]){
    int i;
    for (i=0;i<argc;i++) {
        printf("Argument is %s ",argv[i]);
    }
}

int main(int argc, char*argv[])
{
int isdir(const char *path) {
   struct stat statbuf;
   if (stat(path, &statbuf) != 0)
       return 0;
   return S_ISDIR(statbuf.st_mode);
}
printf("Program started... \n");
showArgs(argc, argv);
if(argc == 2)
{
    if(isdir(argv[1]))
    {
        printf("Calling dir with parameter\n");
        execl("dirname",argv[1],NULL);
    }else{
        printf("invalid dir name\n");
}
}
return 0;
}

最佳答案

您缺少 execl() 的参数。应该是:

execl("/usr/bin/dirname", "dirname", argv[1], (char*)NULL);

第一个参数是要执行的命令的路径,其余参数是argv 数组的元素。 argv[0] 是命令的名称。

您还可以使用 execlp(),它使用 PATH 环境变量搜索命令。那么第一个参数可以只是 "dirname"。但是您仍然需要在 argv[0] 中重复它。

此外,函数不应在 C 中的其他函数内部定义。isdir() 定义应该在之前 main(),而不是里面。

关于c - 如何实现 Unix 命令 "dirname"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48257025/

相关文章:

c - 为什么我一直得到 "error: variable has incomplete type ' struct intVec'?

database - Drupal 7 - 如何将 unix 时间戳插入数据库

c++ - stat() 中 UID 的错误值和 psinfo_t 中错误的 pr_pid

mysql - 从数据库中存储的完整路径中提取目录名

python - 查找模块的目录

c - 在 C 中迭代相同类型的结构成员

你能帮我做这个算法吗 "Shifting a String to right or left"

C:有时会出现段错误?

bash - 遍历子目录并对某些文件执行 awk 脚本

bash - 如何在 bash 中获取给定路径的根目录?