[英]Implementing tar command in c
I'm trying to create a basic version of the linux "tar" command using C, i used perror to see if there are any errors during execution, and i got this 我正在尝试使用C创建linux“ tar”命令的基本版本,我使用perror查看执行期间是否有任何错误,并且得到了
./tar
Error2: Bad file descriptor
and this is what i did so far 这就是我到目前为止所做的
#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");
}
Thanks in advance:) 提前致谢:)
you're opening your tar
file in O_WRONLY
mode, so it truncates the existing file instead of opening it for reading. 您将以O_WRONLY
模式打开tar
文件,因此它会截断现有文件,而不是打开文件进行读取。
When you try to extract from the file you get an error (probably when reading the header), that's expected because file contents are clobbered by the previous (successul) call. 当您尝试从文件中提取文件时,您会收到错误消息(可能是在读取标头时),这是因为文件内容被先前的(成功的)调用所破坏。
Check working examples here: 在此处查看工作示例:
O_RDONLY
他们使用O_RDONLY
To sum it up, my fix: replace 总结一下,我的解决方法:替换
if ((tar_open(&pTar, filename, NULL, O_WRONLY, 0644, TAR_GNU)) == -1)
by 通过
if ((tar_open(&pTar, filename, NULL, O_RDONLY, 0644, TAR_GNU)) == -1)
(I don't think all parameters are useful in read mode, like permissions or tar type, but that should work, it's difficult to find proper examples for that library) (我不认为所有参数在读取模式下都是有用的,例如权限或tar类型,但这应该可以工作,很难为该库找到合适的示例)
For any one referencing to this in the future, 对于将来任何与此相关的人,
while creating the tar - say abc.tar if you have appended the abc.tar (it is also in the same directory and append_tree appends all file, including the one), your abc.tar file, on tar_extract_all, this .tar file (with the same name) is also extracted overwriting the original tar file. 在创建tar时-如果已附加abc.tar(它也位于同一目录中,并且append_tree会附加所有文件(包括一个文件)),则说abc.tar,即abc.tar文件,位于tar_extract_all上,此.tar文件(具有相同名称的文件)也会被提取并覆盖原始tar文件。
atleast this was what causing the mysterious "Invalid argument" for me. 这至少是造成我神秘的“无效论证”的原因。 I fixed it by renaming the original file before extracting. 我通过在提取之前重命名原始文件来修复它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.