gpt4 book ai didi

C++ 使用带字符串数组的 execvp

转载 作者:太空狗 更新时间:2023-10-29 21:18:58 24 4
gpt4 key购买 nike

我正在编写一个程序来执行带有任意数量参数的 Unix 命令。当我使用常规字符串时,我可以毫无问题地接收输入和制作 token 。但是,execvp 只接受一个指针数组,我不确定如何将字符串数组转换为此。这是我拥有的:

#include <cstring>
#include <iostream>
#include <sstream>
#include <string>
#include <unistd.h>
int main()
{
while (true)
{
int argc = 0;
std::istringstream iss;
std::string command;
std::cout << "$> ";
getline(std::cin, command);
iss.str(command);
for (unsigned i = 0; i <= command.length(); i++)
{
if (command[i] == ' ' || command[i] == '\0')
{
argc++;
}
}
std::string arr[argc+1];
for (int i = 0; i < argc; i++)
{
iss >> arr[i];
}
if (arr[0].compare("quit"))
{
break;
}
else
{
char*argv[argc+1];
for (int i = 0; i < argc; i++)
{
argv[i] = arr[i].c_str(); //This line is wrong
}
argv[argc] = NULL;
execvp(argv[0], argv);
}
}
return 0;
}

我尝试了各种方法,但无法弄清楚如何以正确的方式将字符串转换为 char 数组。像 strcpy 这样的方法将不起作用,因为每个参数的长度会有所不同。任何帮助将不胜感激。

最佳答案

你有非常小的错误。

替换:

  1. argv[i] = arr[i].c_str();argv[i] = const_cast<char*>(arr[i].c_str());
  2. if(arr[0].compare("quit"))if(!arr[0].compare("quit"))

一切顺利,这适用于任何编译器。
运行 here

但我有一些建议,使用 fork 使其不会一次只运行一个命令。

示例 here

关于C++ 使用带字符串数组的 execvp,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28712552/

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