如何将目录中具有完整路径的所有文件传递给execv中的参数数组?

时间:2013-02-03 21:17:48

标签: c++ stdvector execvp

我正在尝试读取给定目录中的所有文件(图片)并将其传递给execv。我想启动帧缓冲图像查看器(fbi)。

现在,当我从图片所在的目录中启动它时,它可以工作。我如何操作矢量,这样它不仅可以保存文件名,还可以保存路径+文件名?

int startSlideshow (char* pathtoFBI) {
pid_t fbiPid;

fbiPid = fork();

if (fbiPid == 0) {
    /* this is the child process */
    DIR *pictureDirectory;
    struct dirent *dir;
    int i = 0;
    vector<char*> argVector;
    char pDirectory[] = "/home/pi/bilder/";
    argVector.push_back(pathtoFBI);         /* first Argument is Program name */
    pictureDirectory = opendir(pDirectory);
    if (pictureDirectory){
        while ((dir = readdir(pictureDirectory)) != NULL) {
            i++;
            if (i > 2) {            /* first element is "." second is ".." */
                argVector.push_back(dir->d_name);
            }
        }
        //i -= 2;

    } else ERREXIT("reading picture directory");

    closedir(pictureDirectory);

    argVector.push_back(NULL);
    char** fbiArgv = &argVector[0];
    execvp(pathtoFBI, fbiArgv);         /* pid is taken over by fbi */
    _exit(EXIT_FAILURE);
}

1 个答案:

答案 0 :(得分:1)

鉴于您的代码,您只需要将pDirectory添加到每个文件名:

--- c1.cc       2013-02-04 02:35:47.000000000 +0400
+++ c2.cc       2013-02-04 02:39:03.000000000 +0400
@@ -8,7 +8,7 @@
     DIR *pictureDirectory;
     struct dirent *dir;
     int i = 0;
-    vector<char*> argVector;
+    vector<char*> argVector; vector<string> fpVector;
     char pDirectory[] = "/home/pi/bilder/";
     argVector.push_back(pathtoFBI);         /* first Argument is Program name */
     pictureDirectory = opendir(pDirectory);
@@ -16,7 +16,8 @@
         while ((dir = readdir(pictureDirectory)) != NULL) {
             i++;
             if (i > 2) {            /* first element is "." second is ".." */
-                argVector.push_back(dir->d_name);
+                fpVector.push_back(string(pDirectory) + dir->d_name);
+                argVector.push_back((char*) fpVector.back().c_str());
             }
         }
         //i -= 2;

更一般地说,有Boost Filesystem的absolutecanonical