gpt4 book ai didi

c - libarchive 提取文件时读取的字符过多

转载 作者:行者123 更新时间:2023-12-04 11:31:23 26 4
gpt4 key购买 nike

我已经编写了一个 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 输出。对我来说这似乎是正确的。

我可以看到为什么我的输出不符合预期的两种可能性:
  • 我犯了初学者的错误或
  • 存档文件中的多字节字符与它有关。
  • 最佳答案

    我可能是非常错误的,但这看起来不像一个以空字符结尾的字符串(我认为 archive_read_data 不会解决这个问题)。附加一个 NULL 字符或查看 this并告诉我们进展如何。

    关于c - libarchive 提取文件时读取的字符过多,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2883165/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com