如何将字符串向量传递给 execv [英] How to pass a vector of strings to execv

查看:34
本文介绍了如何将字符串向量传递给 execv的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现构建我的程序参数列表的最简单方法是作为字符串向量.但是, execv 需要一个字符数组作为第二个参数.让它接受字符串向量的最简单方法是什么?

I have found that the easiest way to build my program argument list is as a vector of strings. However, execv expects an array of chars for the second argument. What's the easiest way to get it to accept of vector of strings?

推荐答案

execv() 只接受字符串指针数组.没有办法让它接受其他任何东西.它是一个标准接口,可从所有托管语言调用,而不仅仅是 C++.

execv() accepts only an array of string pointers. There is no way to get it to accept anything else. It is a standard interface, callable from every hosted language, not just C++.

我已经测试编译这个:

std::vector<string> vector;
const char *programname = "abc";

const char **argv = new const char* [vector.size()+2];   // extra room for program name and sentinel
argv [0] = programname;         // by convention, argv[0] is program name
for (int j = 0;  j < vector.size()+1;  ++j)     // copy args
        argv [j+1] = vector[j] .c_str();

argv [vector.size()+1] = NULL;  // end of arguments sentinel is NULL

execv (programname, (char **)argv);

这篇关于如何将字符串向量传递给 execv的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆