在C語言中,可以使用一些開源的庫來實現txt文件的壓縮,比如zlib庫。以下是一個簡單的示例代碼,用來實現txt文件的壓縮:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <zlib.h>
#define CHUNK_SIZE 16384
int compress_file(const char *source_file, const char *dest_file) {
FILE *source = fopen(source_file, "rb");
if (!source) {
fprintf(stderr, "Error opening source file\n");
return -1;
}
FILE *dest = fopen(dest_file, "wb");
if (!dest) {
fprintf(stderr, "Error opening destination file\n");
fclose(source);
return -1;
}
z_stream stream;
stream.zalloc = Z_NULL;
stream.zfree = Z_NULL;
stream.opaque = Z_NULL;
stream.avail_in = 0;
stream.next_in = Z_NULL;
if (deflateInit(&stream, Z_DEFAULT_COMPRESSION) != Z_OK) {
fprintf(stderr, "Error initializing zlib\n");
fclose(source);
fclose(dest);
return -1;
}
unsigned char in[CHUNK_SIZE];
unsigned char out[CHUNK_SIZE];
int ret;
do {
stream.avail_in = fread(in, 1, CHUNK_SIZE, source);
if (ferror(source)) {
fprintf(stderr, "Error reading from source file\n");
deflateEnd(&stream);
fclose(source);
fclose(dest);
return -1;
}
stream.next_in = in;
do {
stream.avail_out = CHUNK_SIZE;
stream.next_out = out;
ret = deflate(&stream, stream.avail_in ? Z_NO_FLUSH : Z_FINISH);
if (ret == Z_STREAM_ERROR) {
fprintf(stderr, "Error compressing data\n");
deflateEnd(&stream);
fclose(source);
fclose(dest);
return -1;
}
fwrite(out, 1, CHUNK_SIZE - stream.avail_out, dest);
if (ferror(dest)) {
fprintf(stderr, "Error writing to destination file\n");
deflateEnd(&stream);
fclose(source);
fclose(dest);
return -1;
}
} while (stream.avail_out == 0);
} while (ret != Z_STREAM_END);
deflateEnd(&stream);
fclose(source);
fclose(dest);
return 0;
}
int main() {
const char *source_file = "source.txt";
const char *dest_file = "compressed.txt";
if (compress_file(source_file, dest_file) != 0) {
fprintf(stderr, "Error compressing file\n");
return -1;
}
printf("File compressed successfully\n");
return 0;
}
在上面的代碼中,我們使用了zlib庫中的deflate函數來實現文件的壓縮。首先打開源文件和目標文件,然后使用deflateInit函數初始化壓縮流。接下來,我們使用一個循環來讀取源文件的數據并進行壓縮,最后寫入目標文件。最后調用deflateEnd函數釋放資源并關閉文件。
請注意,以上代碼僅供參考,實際使用時需要根據實際情況進行適當的修改和調整。