如何读取存档中的文件名? (例如:.img) 我试过下面的代码,但它仍然输出第一个文件的名称。
bool ReadFile(char* file, std::string& name)
{
Header header;
std::fstream file;
file.open(file, std::fstream::in | std::fstream::binary);
if (file.is_open())
{
file.read(reinterpret_cast<char*>(&header), sizeof(Header));
file.seekg(sizeof(Header) + 4, file.cur);
std::string vertemp(header.name, 22);
name = vertemp;
return true;
}
return false;
}
最佳答案
编写另一个可以从头开始读取存档文件的库是不切实际的。为什么要重新发明轮子?我会尽力为您提供尽可能多的信息,以便您按照自己的意愿行事。
使用库归档
有一个用 C 编写的名为 libarchive 的很棒的小库。它能够读取几乎所有你能想到的归档文件,这里只是举几个例子,他们在他们的网站上是这样说的:
Reads a variety of formats, including tar, pax, cpio, zip, xar, lha, ar, cab, mtree, rar, and ISO images.
安装 libarchive
在您开始使用 libarchive 之前,您需要将它安装到您的计算机上。如果您使用的是 debian 基础操作系统,那么您很幸运,否则您可能必须在给定发行版的软件包存储库中搜索该库。或者,您可以按照网站上的文档操作,该文档将向您展示如何 install来自源的库。打开您的终端并输入以下命令:
sudo apt-get install libarchive-dev
示例程序
这个小示例将打印内容的名称,包括存档中文件的完整路径。
#include <iostream>
#include <archive.h>
#include <archive_entry.h>
using namespace std;
int main(int argc, char** argv)
{
struct archive *a;
struct archive_entry *entry;
int r;
a = archive_read_new();
archive_read_support_filter_all(a);
archive_read_support_format_all(a);
r = archive_read_open_filename(a, argv[1], 10240); // Note 1
if (r != ARCHIVE_OK)
return 1;
while (archive_read_next_header(a, &entry) == ARCHIVE_OK) {
cout << archive_entry_pathname(entry) << endl;
archive_read_data_skip(a);
}
r = archive_read_free(a);
if (r != ARCHIVE_OK)
return 1;
}`
编译运行程序
我已经将上面的代码保存在 archivereader.cpp 中
c++ archivereader.cpp -l archive -o archivereader
archivereader Ubuntu.iso
注意事项
不过我已经演示了这个库还有更多内容。
更多例子
这个 git 页面上有一些好的信息:https://github.com/libarchive/libarchive/wiki/Examples
libarchive 官方网站
官方网站包含指向文档和源代码的有用链接。
关于c++ - 如何读取文件中的文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31500340/