用C++写一个tarjin
时间: 2024-05-08 14:22:33 浏览: 10
我认为你想要的是一个tar解压程序,因为tarjin不是一个常见的程序名,而tar文件是一种常见的归档文件格式。以下是一个简单的tar解压程序的C代码示例:
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <time.h>
#include "tar.h"
#define BLOCK_SIZE 512
int main(int argc, char *argv[]) {
if (argc < 2) {
printf("Usage: tarjin <filename>\n");
exit(EXIT_FAILURE);
}
int fd = open(argv[1], O_RDONLY);
if (fd == -1) {
perror("open");
exit(EXIT_FAILURE);
}
char header_buf[512];
int offset = 0;
while (read(fd, header_buf + offset, BLOCK_SIZE - offset) == BLOCK_SIZE - offset) {
struct tar_header *header = (struct tar_header *) header_buf;
if (header->name[0] == '\0') { // End of archive
break;
}
// Calculate size of file
int size = strtol(header->size, NULL, 8);
int blocks = (size + BLOCK_SIZE - 1) / BLOCK_SIZE;
char *buf = malloc(blocks * BLOCK_SIZE);
// Read file contents
if (read(fd, buf, blocks * BLOCK_SIZE) != blocks * BLOCK_SIZE) {
perror("read");
exit(EXIT_FAILURE);
}
// Extract file
int out_fd = open(header->name, O_WRONLY | O_CREAT | O_TRUNC, strtol(header->mode, NULL, 8));
if (out_fd == -1) {
perror("open");
exit(EXIT_FAILURE);
}
if (write(out_fd, buf, size) != size) {
perror("write");
exit(EXIT_FAILURE);
}
close(out_fd);
// Free buffer
free(buf);
// Calculate padding
int padding = BLOCK_SIZE - (offset + BLOCK_SIZE + blocks * BLOCK_SIZE) % BLOCK_SIZE;
if (padding == BLOCK_SIZE) {
padding = 0;
}
// Move to next header
offset = padding;
if (lseek(fd, padding, SEEK_CUR) == -1) {
perror("lseek");
exit(EXIT_FAILURE);
}
}
close(fd);
return 0;
}
```
这个程序使用了一个自定义的tar头部结构体`tar_header`,你需要自己定义。它读取一个tar文件,提取其中的文件并将它们写入文件系统中。你可以自己添加错误处理和其他特性。