gpt4 book ai didi

c - 动态参数传递给 C 中的 execlp() 函数

转载 作者:行者123 更新时间:2023-12-04 18:15:32 25 4
gpt4 key购买 nike

为了简单起见,我修改了我的程序。我想做的是在运行时接受任意数量的参数并将其传递给 execlp() .我正在使用固定长度的二维数组 m[][]这样任何未使用(剩余)的插槽都可以作为 NULL 传递至execlp (在本例中为 m[2][])。

#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<string.h>

int main() {
char m[3][5], name[25];
int i;
strcpy(name, "ls");
strcpy(m[0], "-t");
strcpy(m[1], "-l");
//To make a string appear as NULL (not just as an empty string)
for(i = 0; i < 5; i++)
m[2][i] = '\0'; // or m[2][i] = 0 (I've tried both)
execlp(name, m[0], m[1], m[2], '\0', 0, NULL);
// Does not execute because m[2] is not recognized as NULL
return 0;
}

我该怎么做?

最佳答案

由于您想接受任意数量的参数,因此您应该使用 execvp() 而不是 execlp() :

#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <stdlib.h>

int main(void)
{
char *argv[] = { "ls", "-l", "-t", 0 };
execvp(argv[0], argv);
fprintf(stderr, "Failed to execvp() '%s' (%d: %s)\n", argv[0], errno,
strerror(errno));
return(EXIT_FAILURE);
}
execvp()函数采用数组形式的任意长度参数列表,与 execlp() 不同。您编写的任何单个调用都只需要一个固定长度的参数列表。如果您想容纳 2、3、4、... 参数,您应该为每个不同数量的参数编写单独的调用。其他任何事情都不完全可靠。

关于c - 动态参数传递给 C 中的 execlp() 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11818491/

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