设计思路
- 读取文件:使用
fgets
函数从输入文件逐行读取字符串,注意处理行尾的换行符。
- 内存管理:使用动态内存分配
malloc
和realloc
来灵活管理存储字符串的内存,确保内存使用的高效性。
- 去重操作:将读取到的字符串存储在一个数组中,每次存储前检查是否已存在,避免重复。
- 排序:使用
qsort
函数对字符串数组按长度进行排序。
- 写入文件:将排序后的去重字符串写入输出文件。
核心代码实现
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_LENGTH 1000
// 比较函数,用于qsort按字符串长度排序
int compare(const void *a, const void *b) {
return strlen(*(char **)a) - strlen(*(char **)b);
}
int main() {
FILE *inputFile = fopen("input.txt", "r");
FILE *outputFile = fopen("output.txt", "w");
if (inputFile == NULL || outputFile == NULL) {
perror("Failed to open file");
return 1;
}
char **strings = NULL;
int capacity = 0;
int count = 0;
char buffer[MAX_LENGTH];
while (fgets(buffer, MAX_LENGTH, inputFile) != NULL) {
// 移除换行符
buffer[strcspn(buffer, "\n")] = '\0';
int isDuplicate = 0;
for (int i = 0; i < count; i++) {
if (strcmp(strings[i], buffer) == 0) {
isDuplicate = 1;
break;
}
}
if (!isDuplicate) {
if (count >= capacity) {
capacity = capacity == 0 ? 1 : capacity * 2;
strings = realloc(strings, capacity * sizeof(char *));
}
strings[count] = strdup(buffer);
count++;
}
}
qsort(strings, count, sizeof(char *), compare);
for (int i = 0; i < count; i++) {
fprintf(outputFile, "%s\n", strings[i]);
free(strings[i]);
}
free(strings);
fclose(inputFile);
fclose(outputFile);
return 0;
}