简体   繁体   English

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

[英]How can I run 'ls' with options from a C program?

I want to execute the command ls -a using execv() on a Linux machine as follows: 我想在Linux机器上使用execv()执行命令ls -a ,如下所示:

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

However, this command does not list hidden files. 但是,此命令不会列出隐藏文件。 What am I doing wrong? 我究竟做错了什么?

I'm not sure why you're passing this via /bin/sh ... but since you are, you need to pass all the arguments after -c as a single value because these are now to be interpreted by /bin/sh . 我不确定你为什么要通过/bin/sh传递这个...但是因为你是,你需要将-c之后的所有参数作为单个值传递,因为这些现在由/bin/sh解释。

The example is to compare the shell syntax of 这个例子是比较shell的语法

/bin/sh -c ls -a

to

/bin/sh -c 'ls -a'

The second works, but the first doesn't. 第二个工作,但第一个没有。

So your ptr should be defined as 所以你的ptr应该定义为

char * const ptr[]={"/bin/sh","-c","ls -a" ,NULL}; 

If you need to get the contents of a directory from a program, then this is not the best way - you will effectively have to parse the output of ls , which is generally considered a bad idea . 如果你需要从程序中获取目录的内容,那么这不是最好的方法 - 你将有效地解析ls的输出,这通常被认为是一个坏主意

Instead you can use the libc functions opendir() and readdir() to achieve this. 相反,您可以使用libc函数opendir()readdir()来实现此目的。

Here is a small example program that will iterate over (and list) all files in the current directory: 这是一个小例子程序,它将迭代(并列出)当前目录中的所有文件:

#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;
}

Note the listing will not be sorted, unlike the default ls -a output. 请注意,与默认的ls -a输出不同,列表不会被排序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM