使用 C 创建一个 tar.gz 文件

标签 c linux

大家好,我想从 c 创建 tar.gz 文件 程序

我尝试了 system("tar -zcvf file.tar.gz file") 但它没有用。你有没有更好的选择。这是我的代码

int make_tar() {
    char buff[100];
    DIR *d;
    struct dirent *dir;
    d = opendir(".");

    if (d) {
        while ((dir = readdir(d)) != NULL) {
          if (dir->d_type == DT_REG) {
             sprintf(buff,"%s",dir->d_name);
             system("tar -zxvf buff.tar.xz buff");
         }
    }
    closedir(d);

    return(0);
}

最佳答案

替换

        sprintf(buff,"%s",dir->d_name);
        system("tar -zxvf buff.tar.xz buff");

if (snprintf(buff, sizeof(buff), "tar -czvf %s.tar.gz %s", 
         dir->name, dir->name) /// possible code injection!
    >= sizeof(buff)) 
   exit(EXIT_FAILURE);

fflush(NULL);
int err = system(buff);
if (err) {
   fprintf(stderr, "command failed: %s (%d)\n", buff, err);
   exit(EXIT_FAILURE);
}
else printf ("did %s\n", buff);

可能会有帮助。你应该使用 snprintf(3) (避免 sprintf !!)以避免 buffer overflow ,并且您需要在命令中输入文件的实际名称(不是 buff)。

您最好声明 buff 以包含更多字符,例如char buff[512]; 甚至 static char buff[2*PATH_MAX+25];(可能超过 8 KB)或 char buff[2 *NAME_MAX+30]; 或使用 asprintf(3)

另请阅读 code injection ,这会让你害怕你的代码。想象一下您的程序的恶意用户有一个名为 foo 的文件; rm -rf ..(因为文件名可以包含空格、分号、破折号和点)..

你应该考虑using libtar ...

您应该阅读更多关于 tar(1) 的内容并且可能还考虑将 -T--files-from=FILE 选项传递给它(并让您的程序构造一个临时文本文件列出要备份的每个文件,每行一个;这对于其中包含换行符的文件名不利。

关于使用 C 创建一个 tar.gz 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32657235/

相关文章:

c - IPv6 绑定(bind)失败

ruby-on-rails - rails/Git : can't push my rails code out to the server ('~/git/myapp.git' does not appear to be a git repository)

c - 无法在 kgdb 设置中的某些函数上设置断点

c - 左值无效,函数指针也无效,这有什么用?调用函数就简单多了

c - 显示数组类型的结构程序具有不完整的元素类型

检查子进程的状态

linux - 如何从 Linux Docker 容器中的网络共享恢复 nuget 包

c - 为什么进程要处理阻塞的信号?

c - 尝试访问函数时出现段错误

C 使用 Strtol 将字符串解析为两个整数