UNIX系统中大多数文件IO只需要用到open read write lseek 和 close函数。今天用这几个函数来实现文件的打包和解包。
首先解释下打包和解包的具体功能以及实现原理。这儿的打包只是单纯的将几个文件内容读入一个文件,实现将文件集合打包成一个新文件。然后解包就是通过解析打包形成的打包文件的信息,通过解包函数实现重现原来文件的功能。与通常意义上的压缩解压缩差不多,但是没有压缩功能的实现。
那么要实现这两个功能需要怎么来做呢?我们需要用一个结构体数组来存放文件的信息,比如要打包的文件名和文件大小等,以方便以后解包的时候能够准确还原文件的名称和内容。
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <strings.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
typedef struct Info{
char name[24];
int size;
}inf;
typedef struct infos{
struct Info info[100];
}infos;
int tar(int argc,char *argv[],infos *mytar,int fd2)
{
int n,num = 0,i;
struct stat b;
fd2 = open(argv[argc-1],O_WRONLY|O_CREAT|O_TRUNC,0666);
char buf[100] = {0};
if(-1 == fd2)
{
perror("open tar");
return -1;
}
for(i=0;i<argc-2;i++)
{
strcpy(mytar->info[i]