问题描述
在这个网站上已经用各种不同的解决方案问过这个问题一百万次,但似乎没有一个适合我的情况。
到目前为止,最有前途的是tar -cvf testetest.tar -C folder1 *
,其中folder1包括:
Folder1
>txt1.txt
>folder2
>txt2.txt
在终端中运行以上代码将创建testtest.tar
,其中包括一堆错误消息:
txt1.txt
folder2
>txt2.txt
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
我烦恼的另一行是将*
替换为.
,但是最终包括根目录
解决方法
如在shell中键入*
所见,该shell用文件名列表替换了echo *
。但是除非您专门执行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()
。