以下是一个简单的 C 语言程序,实现了文件去重(dedup)的功能。程序读取一个文件,去除其中重复的行,并将结果输出到另一个文件中。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAX_LINE_LENGTH 1024

int main(int argc, char *argv[]) {
    if (argc != 3) {
        printf("Usage: dedup input_file output_file\n");
        return 1;
    }

    FILE *input_file = fopen(argv[1], "r");
    if (input_file == NULL) {
        printf("Error: cannot open input file %s\n", argv[1]);
        return 1;
    }

    FILE *output_file = fopen(argv[2], "w");
    if (output_file == NULL) {
        printf("Error: cannot open output file %s\n", argv[2]);
        return 1;
    }

    char line[MAX_LINE_LENGTH];
    char *prev_line = NULL;
    while (fgets(line, MAX_LINE_LENGTH, input_file) != NULL) {
        if (prev_line == NULL || strcmp(line, prev_line) != 0) {
            fputs(line, output_file);
        }
        if (prev_line != NULL) {
            free(prev_line);
        }
        prev_line = strdup(line);
    }

    if (prev_line != NULL) {
        free(prev_line);
    }

    fclose(input_file);
    fclose(output_file);

    return 0;
}

该程序使用了标准库函数fgetsfputs来读写文件,使用了strcmp函数来比较两个字符串是否相等,使用了strdup函数来复制字符串。程序还使用了mallocfree函数来动态分配和释放内存。

C语言实现文件去重功能:Dedup 代码示例

原文地址: https://www.cveoy.top/t/topic/lfdo 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录