Linux的
完全没有问题,但我自己无法理解。我正在使用来自http://www.feep.net/libtar/
的libtar我已经删除了几个文件并通过libtar进行了tar。
TAR *pTar;
snprintf(tar_name,sizeof(tar_name),"%s.tar",BACKUP_TASK.path_to_backup);
tar_open(&pTar, tar_name, NULL, O_WRONLY | O_CREAT, 0777, TAR_GNU);
tar_append_tree(pTar, BACKUP_TASK.path_to_backup, BACKUP_TASK.task_name);
//Append vm list to archive
tar_append_file(pTar, "task.xml", "backup.xml");
//Close it
tar_close(pTar);
然后我需要寻找tar,提取一些文件
以下是TAR的真实内容:
#tar tf /home/backup/ftp_templates.tar
ftp_templates/
ftp_templates/d982d6cc-810a-7582-ddec-2c6b6a9d5530.xva.zlib
ftp_templates/51979771-7362-2061-9043-3606682fa0f3.xva.zlib
ftp_templates/f9e5a919-4aa9-a02d-b1ec-3667ecaa4a5b.xva.zlib
backup.xml
我正在尝试列出里面的文件:
TAR *pTar;
char *tarFilename = "/home/backup/ftp_templates.tar";
tar_open(&pTar, tarFilename, NULL, O_RDONLY | TAR_NOOVERWRITE, 0777, TAR_GNU|TAR_VERBOSE);
while(th_read(pTar)==0)
{
puts(pTar->th_buf.name);
}
tar_close(pTar);
但它只给出了
ftp_templates/
ftp_templates/d982d6cc-810a-7582-ddec-2c6b6a9d5530.xva.zlib
如果我尝试使用
提取任何文件tar_extract_file(pTar,"backup.xml");
它创建空文件,大小为0
提取所有文件效果很好。我只是没有找到任何提取单个文件的例子....
tar -xvf /home/backup/ftp_templates.tar backup.xml
这也做得很好,所以tar本身就没问题。
答案 0 :(得分:0)
多数民众赞成我是怎么做到的。工作正常但对我来说不太明显
TAR *pTar;
int i=0;
tar_open(&pTar, xva_filename, 0, O_RDONLY, 0, 0);
while ((i = th_read(pTar)) == 0)
{
//th_print_long_ls(pTar);
//th_print(pTar);
if(strcmp(pTar->th_buf.name,"ova.xml")==0)
{
puts(pTar->th_buf.name);
tar_extract_regfile(pTar,pTar->th_buf.name);
}
if (TH_ISREG(pTar) && tar_skip_regfile(pTar) != 0)
{
fprintf(stderr, "tar_skip_regfile(): %s\n",
strerror(errno));
return;
}
}
答案 1 :(得分:0)
如果要查找许多文件,请首先构建tar的索引:
#include <iostream>
#include <string>
#include <vector>
#include <libtar.h>
#include <fcntl.h>
#include <unistd.h>
using namespace std;
int extract_from_tar(TAR *pTar, const vector<tar_header> &fileList,
const vector<long int> &fileInPos, size_t index)
{
const tar_header &th = fileList[index];
pTar->th_buf = th;
lseek (tar_fd(pTar), fileInPos[index], SEEK_SET);
return tar_extract_regfile(pTar, pTar->th_buf.name);
}
int main()
{
time_t seed = time( NULL );
srand( seed );
vector<tar_header> fileList;
vector<long int> fileInPos;
TAR *pTar = nullptr;
tar_open(&pTar, "test.tar", NULL, O_RDONLY, 0, 0);
//Build index for quick access
int i=0;
while ((i = th_read(pTar)) == 0)
{
if(TH_ISREG(pTar))
{
fileList.push_back(pTar->th_buf);
long fd = tar_fd(pTar);
long int pos = lseek(fd, 0, SEEK_CUR);
fileInPos.push_back(pos);
if (tar_skip_regfile(pTar) != 0) return -1;
}
}
//Extract a random file from archive
if(fileList.size()>0)
cout << "extract_from_tar " << extract_from_tar(pTar, fileList, fileInPos, rand()%fileList.size()) << endl;
tar_close(pTar);
}