如何使用C程序中的选项运行'ls'?

7 c shell

我想执行的命令ls -a使用execv()一台Linux机器上进行如下:

char *const ptr={"/bin/sh","-c","ls","-a" ,NULL};
execv("/bin/sh",ptr);
Run Code Online (Sandbox Code Playgroud)

但是,此命令不会列出隐藏文件.我究竟做错了什么?

小智 9

我不确定你为什么要通过这个/bin/sh...但是既然你是,你需要将所有的参数-c作为单个值传递,因为现在要解释它们/bin/sh.

这个例子是比较shell的语法

/bin/sh -c ls -a
Run Code Online (Sandbox Code Playgroud)

/bin/sh -c 'ls -a'
Run Code Online (Sandbox Code Playgroud)

第二个工作,但第一个没有.

所以你的ptr定义应该是

char * const ptr[]={"/bin/sh","-c","ls -a" ,NULL}; 
Run Code Online (Sandbox Code Playgroud)

  • 请注意,调用外部命令不需要shell:您只需使用`{"/ bin/ls"," - a",NULL}`. (2认同)
  • @deltab - 是的,如果需要`/ bin/sh`那么`system()`也可以.我只是借此机会解释为什么`sh -c`需要一个参数中的参数:-) (2认同)

Dig*_*uma 5

如果你需要从程序中获取目录的内容,那么这不是最好的方法 - 你将有效地解析输出ls,这通常被认为是一个坏主意.

相反,你可以使用libc的功能opendir()readdir()实现这一目标.

这是一个小例子程序,它将迭代(并列出)当前目录中的所有文件:

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

int main (int argc, char **argv) {
    DIR *dirp;
    struct dirent *dp;

    dirp = opendir(".");
    if (!dirp) {
        perror("opendir()");
        exit(1);
    }

    while ((dp = readdir(dirp))) {
        puts(dp->d_name);
    }

    if (errno) {
        perror("readdir()");
        exit(1);
    }

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

请注意,与默认ls -a输出不同,列表不会被排序.