c - 如何在一行中为 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
我厌倦的另一条线是*
用.
但是最终包括根目录的替换
解决方案
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()
.
推荐阅读
- html - 溢出:自动在台式机上工作,但不能在移动设备上工作
- c# - 如何在 Hangman C# 中输出剩余/使用的字母
- excel - 将 Bash 中的 CSV 读入字典/关联数组
- django - Django model_name.item.add(item) 将项目添加到模型中的所有记录
- javascript - 按从一天中的时间开始的顺序从数组中输出图像
- firebase - 允许读取任何用户的最佳 Firebase 规则
- python - Python Tkinter:_tkinter.TclError:图像“pyimage1”不存在
- php - php 选择控件更改布局
- telegram - 使用 Telethon 在所有 Telegram 组中搜索单词
- r - data$Y_i1 中的错误:“闭包”类型的对象不可子设置