将文件压缩成zip然后下载到浏览器
时间: 2023-04-04 13:04:22 浏览: 148
您可以使用以下代码将文件压缩成zip并下载到浏览器:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <dirent.h>
#include <time.h>
#include <utime.h>
#include <zlib.h>
#define CHUNK 16384
int compress_file(const char *src, const char *dst)
{
int ret;
unsigned have;
z_stream strm;
unsigned char in[CHUNK];
unsigned char out[CHUNK];
FILE *source = NULL;
FILE *dest = NULL;
source = fopen(src, "rb");
if (source == NULL) {
fprintf(stderr, "Failed to open file %s: %s\n", src, strerror(errno));
return -1;
}
dest = fopen(dst, "wb");
if (dest == NULL) {
fprintf(stderr, "Failed to open file %s: %s\n", dst, strerror(errno));
fclose(source);
return -1;
}
strm.zalloc = Z_NULL;
strm.zfree = Z_NULL;
strm.opaque = Z_NULL;
ret = deflateInit(&strm, Z_DEFAULT_COMPRESSION);
if (ret != Z_OK) {
fprintf(stderr, "Failed to initialize zlib: %s\n", strm.msg);
fclose(source);
fclose(dest);
return -1;
}
do {
strm.avail_in = fread(in, 1, CHUNK, source);
if (ferror(source)) {
fprintf(stderr, "Failed to read file %s: %s\n", src, strerror(errno));
deflateEnd(&strm);
fclose(source);
fclose(dest);
return -1;
}
if (strm.avail_in == 0)
break;
strm.next_in = in;
do {
strm.avail_out = CHUNK;
strm.next_out = out;
ret = deflate(&strm, Z_FINISH);
if (ret == Z_STREAM_ERROR) {
fprintf(stderr, "Failed to compress file %s: %s\n", src, strm.msg);
deflateEnd(&strm);
fclose(source);
fclose(dest);
return -1;
}
have = CHUNK - strm.avail_out;
if (fwrite(out, 1, have, dest) != have || ferror(dest)) {
fprintf(stderr, "Failed to write compressed data to file %s: %s\n", dst, strerror(errno));
deflateEnd(&strm);
fclose(source);
fclose(dest);
return -1;
}
} while (strm.avail_out == 0);
} while (ret != Z_STREAM_END);
deflateEnd(&strm);
fclose(source);
fclose(dest);
return 0;
}
int main(int argc, char *argv[])
{
if (argc != 3) {
fprintf(stderr, "Usage: %s <source file> <destination file>\n", argv[0]);
return 1;
}
if (compress_file(argv[1], argv[2]) != 0) {
fprintf(stderr, "Failed to compress file %s\n", argv[1]);
return 1;
}
return 0;
}
```
您可以将源文件和目标文件的路径作为命令行参数传递给该程序。例如,如果您要将文件`/path/to/file.txt`压缩成`/path/to/file.zip`,则可以运行以下命令:
```
$ ./compress /path/to/file.txt /path/to/file.zip
```
该程序将使用zlib库将文件压缩成zip格式,并将压缩后的文件保存到目标文件中。您可以在浏览器中下载该文件。