【问题标题】:libarchive reads too many chars when extracting a file提取文件时,libarchive 读取了太多字符
【发布时间】:2010-05-21 14:58:09
【问题描述】:

我编写了一个 C 程序来使用 libarchive 从 tar 存档中提取文件。

我想从此档案中提取一个文件并将其打印到标准输出。 但我得到了额外的字符。这是垃圾,但它来自另一个文件(可能在存档中与它相邻。)我希望输出结束于</html>

这里是this tar file的代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "archive.h"
#include "archive_entry.h"


int main (int argc, const char * argv[]) 
{
    struct archive *a;
    struct archive_entry *entry;
    int r;
    int64_t entry_size;
    a = archive_read_new();
    archive_read_support_compression_none(a);
    archive_read_support_format_tar(a);
    r = archive_read_open_filename(a, "0000.tar", 1024);
    if (r != ARCHIVE_OK)
    {
        printf("archive not found");
    }
    else 
    {
        while (archive_read_next_header(a, &entry) == ARCHIVE_OK) 
        {
            const char *currentFile = archive_entry_pathname(entry);
            char *fileContents;
            entry_size = archive_entry_size(entry); //get the size of the file
            fileContents = malloc(entry_size); //alloc enough for string - from my testing I see that this is how many bytes tar and ls report from command line
            archive_read_data(a, fileContents, entry_size); //read data into fileContents string for the HTML file size
            if(strcmp(currentFile, "vendar-definition.html") == 0)
            {
                printf("file name = %s, size = %lld\n", currentFile, entry_size);
                printf("%s\n\n", fileContents); //this output over-reads chars from another file in this tar file
            }           
            free(fileContents); //free the C string because I malloc'd
        }
    }
    printf("exit");
    return 0;
}

libarchive 2.8.3 在 mac os X 10.6.3 上编译。 gcc 4.2 x86_64

ls -l vendar-definition.html 给我1921 的文件大小。所以显示tar tfv 0000.tar | grep vendar-definition.html。因此报告说明文件大小的 C 输出。在我看来,这似乎是正确的。

我可以看出为什么我的输出不符合预期的两种可能性:

  1. 我犯了初学者的错误或
  2. 存档文件中的多字节字符与此有关。

【问题讨论】:

  • 如果 fileContents 和 currentFile 在 while 块之外声明会不会更好?
  • 另外,我的 gcc 在尝试使用 char* 而不是 void* 作为 fileContents 时会抱怨。这样做,一个简单的 printf("%s", fileContents) 就解决了。请检查它是否适合您。

标签: c malloc tar


【解决方案1】:

我可能 非常 错了,但这看起来不像一个以 null 结尾的字符串(我不认为 archive_read_data 会处理这个问题)。附加一个 NULL 字符或查看 this 并告诉我们它是怎么回事。

【讨论】:

  • 显然不是。完美,那个链接让我直截了当。谢谢!
【解决方案2】:

我怀疑你没有阅读太多字符,而只是打印太多。

您正在使用%s 说明符将文件内容输出到printf,它期望输入是以空值结尾的字符串。存档中文件的内容可能不是以空值结尾的,并且可以在中间包含任意空值。

尝试像这样输出:

fwrite(fileContents, sizeof(char), entry_size, stdout);

【讨论】:

    猜你喜欢
    • 2014-10-09
    • 2015-06-15
    • 2016-03-24
    • 1970-01-01
    • 2017-11-12
    • 1970-01-01
    • 1970-01-01
    • 2021-08-24
    • 1970-01-01
    相关资源
    最近更新 更多