首页 > 解决方案 > 如何在一行中为 execv() 压缩没有父文件和根文件

问题描述

这个问题在这个网站上被问了一百万次,有各种不同的解决方案,但似乎没有一个适合我的情况。

到目前为止,最有希望的是tar -cvf testetest.tar -C folder1 *folder1 包括:

Folder1
    >txt1.txt
    >folder2
        >txt2.txt

在终端中运行上面的代码会创建testtest.tar其中包括一堆错误消息:

txt1.txt
folder2
    >txt2.txt

但是,当通过 execv 在函数中运行时,如下所示:

pid_t archive = fork();
    switch(archive)
    {
        case -1 :
        {
            printf("fork() failed\n");
            break;
        }
        case 0 :
        {
            if( strcmp(getFileExtension(finalArchiveName), "tar") == 0)
            {
                char* args[] = {"/usr/bin/tar","-cvf", finalArchiveName, "-C", "dest", "*", NULL};
                int error = execv("/usr/bin/tar", args);    
                if(error == -1){
                    perror("Error when archiving");
                    exit(EXIT_FAILURE);
                }
                else{
                    exit(EXIT_SUCCESS);
                }
                break;
            }
//... (not including the whole function, only the part i feel is relevant to the question)

它返回/usr/bin/tar: *: Cannot stat: No such file or directory

我厌倦的另一条线是*.但是最终包括根目录的替换

标签: carchiveexecv

解决方案


shell 将 替换*为文件名列表,正如您通过键入echo *shell 所看到的那样。但是在对 的调用中没有 shell execv,除非你专门执行一个 shell:

char* args[] = {"sh", "-c", "tar /usr/bin/tar -cvf testetest.tar -C dest *", NULL};
int error = execv("/bin/sh", args);

在这种情况下,system() 通常是一个更简单的选择。

如果要创建文件名列表以作为参数传递给命令行实用程序,请查看glob().


推荐阅读