我试图用c创建一个linux“tar”命令的基本版本,我用perror查看在执行期间是否有任何错误,我得到了这个
./tar
Error2: Bad file descriptor
到目前为止我就是这么做的
#include <stdio.h>
#include <libtar.h>
#include <fcntl.h>
int main(void)
{
TAR *pTar;
char *prefix = ".";
char *filename = "file.tar";
if ((tar_open(&pTar, filename, NULL, O_WRONLY, 0644, TAR_GNU)) == -1)
perror("Error1");
else if ((tar_extract_all(pTar, prefix)) == -1)
perror("Error2");
else if ((tar_close(pTar)) == -1)
perror("Error3");
}
提前谢谢:)
最佳答案
您在tar
模式中打开O_WRONLY
文件,因此它截断了现有文件,而不是打开它来进行读取。
当您试图从文件中提取时,您会得到一个错误(可能是在读取头文件时),这是意料之中的,因为文件内容被前一个(成功的)调用所破坏。
检查以下工作示例:
读取tar文件:how to untar file in memory (c programming)?。它们使用O_RDONLY
创建tar文件:using libtar library in c。看起来像你的代码,除了是写的,不是读的。
总而言之,我的解决方案是:替换
if ((tar_open(&pTar, filename, NULL, O_WRONLY, 0644, TAR_GNU)) == -1)
通过
if ((tar_open(&pTar, filename, NULL, O_RDONLY, 0644, TAR_GNU)) == -1)
(我不认为所有的参数在读取模式下都有用,比如权限或tar类型,但是这应该有效,很难为该库找到合适的示例)