【发布时间】: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 输出。在我看来,这似乎是正确的。
我可以看出为什么我的输出不符合预期的两种可能性:
- 我犯了初学者的错误或
- 存档文件中的多字节字符与此有关。
【问题讨论】:
-
如果 fileContents 和 currentFile 在 while 块之外声明会不会更好?
-
另外,我的 gcc 在尝试使用 char* 而不是 void* 作为 fileContents 时会抱怨。这样做,一个简单的 printf("%s", fileContents) 就解决了。请检查它是否适合您。