引言:为什么需要掌握C语言文本批处理?
在当今数据驱动的时代,文本文件批处理是每个程序员必备的核心技能。无论是处理日志文件、分析CSV数据、批量重命名文件,还是进行数据清洗,C语言凭借其高效的文件操作和底层控制能力,成为解决这些任务的理想选择。
C语言在文本批处理方面具有独特优势:
高性能
:直接操作系统API,无额外运行时开销
精细控制
:精确控制内存使用和文件指针位置
跨平台
:标准库函数在所有主流操作系统上一致
系统级集成
:与Shell脚本、系统工具无缝配合
本文将从基础概念开始,逐步深入到高级技巧,通过大量实战案例帮助你掌握C语言文本批处理的精髓。
第一部分:C语言文件操作基础
1.1 文件流概念与标准库函数
C语言使用文件流(FILE*)来操作文件,这是理解文件处理的基础。文件流是C标准库提供的抽象层,它将底层系统调用封装成简单易用的函数。
文件打开模式详解
#include
int main() {
// 1. 读取模式 (r) – 文件必须存在
FILE *f1 = fopen(“input.txt”, “r”);
// 2. 写入模式 (w) – 创建新文件或清空已有文件
FILE *f2 = fopen(“output.txt”, “w”);
// 3. 追加模式 (a) – 在文件末尾添加内容
FILE *f3 = fopen(“log.txt”, “a”);
// 4. 读写模式 (r+) – 读写已存在文件
FILE *f4 = fopen(“data.txt”, “r+”);
// 5. 读写创建模式 (w+) – 读写新文件或清空已有文件
FILE *f5 = fopen(“temp.txt”, “w+”);
// 6. 读写追加模式 (a+) – 读写,写入时追加到末尾
FILE *f6 = fopen(“append.txt”, “a+”);
// 检查文件是否成功打开
if (f1 == NULL) {
perror(“打开文件失败”);
return 1;
}
// 关闭文件
fclose(f1);
fclose(f2);
fclose(f3);
fclose(f4);
fclose(f5);
fclose(f6);
return 0;
}
文件读写函数对比
函数
用途
适用场景
性能特点
fgetc()
读取单个字符
逐字符处理
慢,但内存占用小
fgets()
读取一行
文本行处理
中等,常用
fread()
读取二进制块
大数据块
快,适合大文件
fscanf()
格式化读取
结构化数据
中等,但容易出错
fputc()
写入单个字符
逐字符输出
慢
fputs()
写入字符串
文本行输出
中等
fwrite()
写入二进制块
大数据块
快
fprintf()
格式化写入
结构化输出
中等
1.2 基础文件读写实战
案例1:逐行读取并处理文本文件
#include
#include
#include
#define MAX_LINE_LENGTH 1024
// 统计文件中每行的字符数和单词数
void analyze_text_file(const char *filename) {
FILE *file = fopen(filename, “r”);
if (file == NULL) {
perror(“无法打开文件”);
return;
}
char line[MAX_LINE_LENGTH];
int line_number = 0;
int total_chars = 0;
int total_words = 0;
printf(“文件分析报告: %s\n”, filename);
printf(“=====================================\n”);
while (fgets(line, sizeof(line), file) != NULL) {
line_number++;
int char_count = strlen(line);
int word_count = 0;
int in_word = 0;
// 统计单词数
for (int i = 0; i < char_count; i++) {
if (isspace(line[i])) {
in_word = 0;
} else if (!in_word) {
word_count++;
in_word = 1;
}
}
// 移除换行符用于显示
if (char_count > 0 && line[char_count – 1] == ‘\n’) {
line[char_count – 1] = ‘\0’;
char_count–;
}
printf(“第%2d行: %2d字符, %2d单词 | %s\n”,
line_number, char_count, word_count, line);
total_chars += char_count;
total_words += word_count;
}
printf(“\n总计: %d行, %d字符, %d单词\n”,
line_number, total_chars, total_words);
fclose(file);
}
int main() {
// 创建测试文件
FILE *test = fopen(“test.txt”, “w”);
fprintf(test, “Hello World\n”);
fprintf(test, “C Language Programming\n”);
fprintf(test, “File Processing Example\n”);
fclose(test);
analyze_text_file(“test.txt”);
return 0;
}
案例2:CSV文件解析器
#include
#include
#include
#define MAX_FIELDS 20
#define MAX_FIELD_LENGTH 100
typedef struct {
char fields[MAX_FIELDS][MAX_FIELD_LENGTH];
int field_count;
} CSVRow;
// 解析CSV行
int parse_csv_row(char *line, CSVRow *row) {
row->field_count = 0;
char *token = strtok(line, “,”);
while (token != NULL && row->field_count < MAX_FIELDS) { // 去除字段两端的空白和引号 char *start = token; char *end = token + strlen(token) - 1; // 去除前导空白 while (*start && isspace(*start)) start++; // 去除尾部空白 while (end > start && isspace(*end)) end–;
// 处理引号
if (*start == ‘”‘ && *end == ‘”‘ && end > start) {
start++;
*end = ‘\0’;
} else {
*(end + 1) = ‘\0’;
}
strncpy(row->fields[row->field_count], start, MAX_FIELD_LENGTH – 1);
row->fields[row->field_count][MAX_FIELD_LENGTH – 1] = ‘\0’;
row->field_count++;
token = strtok(NULL, “,”);
}
return row->field_count;
}
// 处理CSV文件
void process_csv_file(const char *filename) {
FILE *file = fopen(filename, “r”);
if (file == NULL) {
perror(“无法打开CSV文件”);
return;
}
char line[1024];
int row_count = 0;
CSVRow header;
// 读取标题行
if (fgets(line, sizeof(line), file)) {
parse_csv_row(line, &header);
printf(“CSV文件头: “);
for (int i = 0; i < header.field_count; i++) {
printf("[%s] ", header.fields[i]);
}
printf("\n");
}
// 处理数据行
while (fgets(line, sizeof(line), file)) {
CSVRow row;
if (parse_csv_row(line, &row)) {
row_count++;
printf("第%d行: ", row_count);
for (int i = 0; i < row.field_count; i++) {
printf("%s\t", row.fields[i]);
}
printf("\n");
}
}
printf("\n共处理了 %d 行数据\n", row_count);
fclose(file);
}
int main() {
// 创建测试CSV
FILE *csv = fopen("data.csv", "w");
fprintf(csv, "Name,Age,Department,Salary\n");
fprintf(csv, "Alice,25,Engineering,75000\n");
fprintf(csv, "Bob,30,Marketing,65000\n");
fprintf(csv, "Charlie,28,Sales,70000\n");
fclose(csv);
process_csv_file("data.csv");
return 0;
}
1.3 错误处理与资源管理
完整的错误处理模式
#include
#include
#include
#include
// 安全的文件操作包装器
FILE* safe_fopen(const char *filename, const char *mode) {
FILE *file = fopen(filename, mode);
if (file == NULL) {
fprintf(stderr, “错误: 无法打开文件 ‘%s’ (模式: %s)\n”, filename, mode);
fprintf(stderr, “系统错误: %s\n”, strerror(errno));
return NULL;
}
return file;
}
// 安全的内存分配
void* safe_malloc(size_t size) {
void *ptr = malloc(size);
if (ptr == NULL) {
fprintf(stderr, “错误: 内存分配失败,需要 %zu 字节\n”, size);
exit(EXIT_FAILURE);
}
return ptr;
}
// 安全的文件复制函数
int safe_file_copy(const char *source, const char *dest) {
FILE *src = NULL, *dst = NULL;
char buffer[4096];
size_t bytes;
int result = -1;
src = safe_fopen(source, “rb”);
if (src == NULL) goto cleanup;
dst = safe_fopen(dest, “wb”);
if (dst == NULL) goto cleanup;
while ((bytes = fread(buffer, 1, sizeof(buffer), src)) > 0) {
if (fwrite(buffer, 1, bytes, dst) != bytes) {
fprintf(stderr, “错误: 写入数据不完整\n”);
goto cleanup;
}
}
if (ferror(src)) {
fprintf(stderr, “错误: 读取源文件失败\n”);
goto cleanup;
}
result = 0; // 成功
cleanup:
if (src) fclose(src);
if (dst) {
fclose(dst);
if (result != 0) {
// 如果失败,删除目标文件
remove(dest);
}
}
return result;
}
int main() {
// 创建源文件
FILE *f = fopen(“source.txt”, “w”);
fprintf(f, “This is a test file.\n”);
fprintf(f, “It contains multiple lines.\n”);
fclose(f);
// 安全复制
if (safe_file_copy(“source.txt”, “destination.txt”) == 0) {
printf(“文件复制成功!\n”);
} else {
printf(“文件复制失败!\n”);
}
return 0;
}
第二部分:批量文件操作技术
2.1 目录遍历与文件发现
跨平台目录遍历
#include
#include
#include
#include
#include
#include
// 检查是否为目录
int is_directory(const char *path) {
struct stat path_stat;
if (stat(path, &path_stat) != 0) {
return 0;
}
return S_ISDIR(path_stat.st_mode);
}
// 检查文件扩展名
int has_extension(const char *filename, const char *ext) {
const char *dot = strrchr(filename, ‘.’);
if (dot == NULL) return 0;
return strcmp(dot, ext) == 0;
}
// 递归查找特定扩展名的文件
void find_files_by_extension(const char *base_path, const char *ext, int recursive) {
DIR *dir = opendir(base_path);
if (dir == NULL) {
perror(“无法打开目录”);
return;
}
struct dirent *entry;
while ((entry = readdir(dir)) != NULL) {
// 跳过 . 和 ..
if (strcmp(entry->d_name, “.”) == 0 || strcmp(entry->d_name, “..”) == 0) {
continue;
}
char full_path[1024];
snprintf(full_path, sizeof(full_path), “%s/%s”, base_path, entry->d_name);
if (is_directory(full_path)) {
if (recursive) {
find_files_by_extension(full_path, ext, recursive);
}
} else if (has_extension(entry->d_name, ext)) {
printf(“%s\n”, full_path);
}
}
closedir(dir);
}
int main() {
// 在当前目录查找所有 .c 文件
printf(“查找所有 .c 文件:\n”);
find_files_by_extension(“.”, “.c”, 1);
return 0;
}
2.2 批量文件重命名
案例:批量重命名照片文件
#include
#include
#include
#include
#include
#include
// 生成基于时间戳的新文件名
void generate_timestamp_filename(const char *old_name, char *new_name, int counter) {
time_t now = time(NULL);
struct tm *tm_info = localtime(&now);
// 提取原文件扩展名
const char *ext = strrchr(old_name, ‘.’);
if (ext == NULL) ext = “”;
// 格式: YYYYMMDD_HHMMSS_counter.ext
sprintf(new_name, “%04d%02d%02d_%02d%02d%02d_%03d%s”,
tm_info->tm_year + 1900,
tm_info->tm_mon + 1,
tm_info->tm_mday,
tm_info->tm_hour,
tm_info->tm_min,
tm_info->tm_sec,
counter,
ext);
}
// 批量重命名目录中的文件
void batch_rename_files(const char *dir_path, const char *prefix) {
DIR *dir = opendir(dir_path);
if (dir == NULL) {
perror(“无法打开目录”);
return;
}
struct dirent *entry;
int counter = 1;
int renamed_count = 0;
printf(“开始批量重命名…\n”);
while ((entry = readdir(dir)) != NULL) {
// 跳过 . 和 ..
if (strcmp(entry->d_name, “.”) == 0 || strcmp(entry->d_name, “..”) == 0) {
continue;
}
// 只处理文件,不处理子目录
char full_path[1024];
snprintf(full_path, sizeof(full_path), “%s/%s”, dir_path, entry->d_name);
if (is_directory(full_path)) {
continue;
}
// 生成新文件名
char new_name[256];
if (prefix && strlen(prefix) > 0) {
const char *ext = strrchr(entry->d_name, ‘.’);
if (ext == NULL) ext = “”;
sprintf(new_name, “%s_%03d%s”, prefix, counter, ext);
} else {
generate_timestamp_filename(entry->d_name, new_name, counter);
}
// 构建完整路径
char new_full_path[1024];
snprintf(new_full_path, sizeof(new_full_path), “%s/%s”, dir_path, new_name);
// 执行重命名
if (rename(full_path, new_full_path) == 0) {
printf(“重命名: %s -> %s\n”, entry->d_name, new_name);
renamed_count++;
counter++;
} else {
perror(“重命名失败”);
}
}
printf(“完成!共重命名 %d 个文件\n”, renamed_count);
closedir(dir);
}
int main() {
// 创建测试目录和文件
mkdir(“test_photos”, 0755);
FILE *f1 = fopen(“test_photos/photo1.jpg”, “w”);
FILE *f2 = fopen(“test_photos/photo2.jpg”, “w”);
FILE *f3 = fopen(“test_photos/photo3.jpg”, “w”);
if (f1) fclose(f1);
if (f2) fclose(f2);
if (f3) fclose(f3);
// 批量重命名
batch_rename_files(“test_photos”, “IMG”);
return 0;
}
2.3 文件内容批量替换
案例:批量替换文本文件中的字符串
#include
#include
#include
#include
#define MAX_LINE_LENGTH 8192
// 在单个文件中替换字符串
int replace_in_file(const char *filename, const char *old_str, const char *new_str) {
FILE *src = fopen(filename, “r”);
if (src == NULL) {
perror(“无法打开源文件”);
return -1;
}
// 创建临时文件
char temp_filename[1024];
snprintf(temp_filename, sizeof(temp_filename), “%s.tmp”, filename);
FILE *dst = fopen(temp_filename, “w”);
if (dst == NULL) {
perror(“无法创建临时文件”);
fclose(src);
return -1;
}
char line[MAX_LINE_LENGTH];
int replacements = 0;
int line_num = 0;
while (fgets(line, sizeof(line), src)) {
line_num++;
char *pos = line;
char *new_pos;
char buffer[MAX_LINE_LENGTH * 2] = {0};
char *buf_ptr = buffer;
int buf_remaining = sizeof(buffer) – 1;
// 在当前行中查找并替换所有出现
while ((new_pos = strstr(pos, old_str)) != NULL) {
// 复制替换前的部分
int len = new_pos – pos;
if (len > 0) {
strncpy(buf_ptr, pos, len);
buf_ptr += len;
buf_remaining -= len;
}
// 复制新字符串
int new_len = strlen(new_str);
if (new_len > 0) {
strncpy(buf_ptr, new_str, new_len);
buf_ptr += new_len;
buf_remaining -= new_len;
}
replacements++;
pos = new_pos + strlen(old_str);
}
// 复制剩余部分
if (*pos) {
strncpy(buf_ptr, pos, buf_remaining);
}
// 写入临时文件
fputs(buffer, dst);
}
fclose(src);
fclose(dst);
// 替换原文件
if (replacements > 0) {
if (rename(temp_filename, filename) != 0) {
perror(“无法替换原文件”);
remove(temp_filename);
return -1;
}
printf(“文件 %s: 完成 %d 处替换\n”, filename, replacements);
} else {
remove(temp_filename);
}
return replacements;
}
// 批量替换目录中所有匹配文件的内容
void batch_replace_in_files(const char *dir_path, const char *ext,
const char *old_str, const char *new_str) {
DIR *dir = opendir(dir_path);
if (dir == NULL) {
perror(“无法打开目录”);
return;
}
struct dirent *entry;
int total_replacements = 0;
int files_processed = 0;
while ((entry = readdir(dir)) != NULL) {
if (strcmp(entry->d_name, “.”) == 0 || strcmp(entry->d_name, “..”) == 0) {
continue;
}
if (has_extension(entry->d_name, ext)) {
char full_path[1024];
snprintf(full_path, sizeof(full_path), “%s/%s”, dir_path, entry->d_name);
int result = replace_in_file(full_path, old_str, new_str);
if (result >= 0) {
total_replacements += result;
files_processed++;
}
}
}
closedir(dir);
printf(“\n批量替换完成!\n”);
printf(“处理文件数: %d\n”, files_processed);
printf(“总替换次数: %d\n”, total_replacements);
}
int main() {
// 创建测试文件
mkdir(“test_replace”, 0755);
FILE *f1 = fopen(“test_replace/file1.txt”, “w”);
fprintf(f1, “Hello World\n”);
fprintf(f1, “This is a test file.\n”);
fprintf(f1, “World is beautiful.\n”);
fclose(f1);
FILE *f2 = fopen(“test_replace/file2.txt”, “w”);
fprintf(f2, “World of programming\n”);
fprintf(f2, “Welcome to the World\n”);
fclose(f2);
// 批量替换
batch_replace_in_files(“test_replace”, “.txt”, “World”, “C Language”);
return 0;
}
第三部分:高级文本处理技术
3.1 内存映射文件处理
内存映射(Memory Mapping)是一种高效的文件处理方式,特别适合大文件处理。
#include
#include
#include
#include
#include
#include
#include
#include
// 使用内存映射处理大文件
void process_large_file_mmap(const char *filename) {
int fd = open(filename, O_RDONLY);
if (fd < 0) {
perror("无法打开文件");
return;
}
struct stat sb;
if (fstat(fd, &sb) < 0) {
perror("无法获取文件信息");
close(fd);
return;
}
if (!S_ISREG(sb.st_mode)) {
fprintf(stderr, "不是普通文件\n");
close(fd);
return;
}
// 映射文件到内存
char *data = mmap(NULL, sb.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
if (data == MAP_FAILED) {
perror("内存映射失败");
close(fd);
return;
}
// 处理文件内容(示例:统计行数和单词数)
size_t file_size = sb.st_size;
size_t line_count = 0;
size_t word_count = 0;
int in_word = 0;
for (size_t i = 0; i < file_size; i++) {
char c = data[i];
if (c == '\n') {
line_count++;
}
if (isspace(c)) {
in_word = 0;
} else if (!in_word) {
word_count++;
in_word = 1;
}
}
printf("文件 %s 的统计信息:\n", filename);
printf("大小: %zu 字节\n", file_size);
printf("行数: %zu\n", line_count);
printf("单词数: %zu\n", word_count);
// 清理
munmap(data, sb.st_size);
close(fd);
}
// 使用内存映射进行快速搜索
void search_in_file_mmap(const char *filename, const char *search_term) {
int fd = open(filename, O_RDONLY);
if (fd < 0) {
perror("无法打开文件");
return;
}
struct stat sb;
if (fstat(fd, &sb) < 0) {
perror("无法获取文件信息");
close(fd);
return;
}
char *data = mmap(NULL, sb.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
if (data == MAP_FAILED) {
perror("内存映射失败");
close(fd);
return;
}
size_t term_len = strlen(search_term);
size_t found_count = 0;
// 简单的线性搜索
for (size_t i = 0; i <= sb.st_size - term_len; i++) {
if (memcmp(data + i, search_term, term_len) == 0) {
// 找到匹配,计算行号
size_t line_num = 1;
for (size_t j = 0; j < i; j++) {
if (data[j] == '\n') line_num++;
}
printf("在第 %zu 行找到匹配\n", line_num);
found_count++;
}
}
printf("总共找到 %zu 个匹配\n", found_count);
munmap(data, sb.st_size);
close(fd);
}
int main() {
// 创建大文件用于测试
FILE *f = fopen("large.txt", "w");
for (int i = 0; i < 1000; i++) {
fprintf(f, "Line %d: This is a test line with some words.\n", i);
}
fclose(f);
process_large_file_mmap("large.txt");
search_in_file_mmap("large.txt", "test");
return 0;
}
3.2 并行文件处理
使用多线程加速批量文件处理。
#include
#include
#include
#include
#include
#define MAX_FILES 1000
#define THREAD_COUNT 4
typedef struct {
char filename[1024];
int processed;
} FileTask;
typedef struct {
FileTask *tasks;
int task_count;
int start_index;
int end_index;
const char *old_str;
const char *new_str;
} ThreadData;
// 线程函数:处理文件块
void* process_file_batch(void *arg) {
ThreadData *data = (ThreadData*)arg;
for (int i = data->start_index; i < data->end_index; i++) {
if (data->tasks[i].processed == 0) {
// 调用前面定义的替换函数
int result = replace_in_file(data->tasks[i].filename,
data->old_str, data->new_str);
if (result >= 0) {
data->tasks[i].processed = 1;
printf(“线程 %ld 处理了 %s\n”, pthread_self(), data->tasks[i].filename);
}
}
}
return NULL;
}
// 并行批量替换
void parallel_batch_replace(const char *dir_path, const char *ext,
const char *old_str, const char *new_str) {
DIR *dir = opendir(dir_path);
if (dir == NULL) {
perror(“无法打开目录”);
return;
}
// 收集所有文件
FileTask tasks[MAX_FILES];
int task_count = 0;
struct dirent *entry;
while ((entry = readdir(dir)) != NULL && task_count < MAX_FILES) {
if (strcmp(entry->d_name, “.”) == 0 || strcmp(entry->d_name, “..”) == 0) {
continue;
}
if (has_extension(entry->d_name, ext)) {
snprintf(tasks[task_count].filename, sizeof(tasks[task_count].filename),
“%s/%s”, dir_path, entry->d_name);
tasks[task_count].processed = 0;
task_count++;
}
}
closedir(dir);
if (task_count == 0) {
printf(“没有找到匹配的文件\n”);
return;
}
printf(“找到 %d 个文件,使用 %d 个线程处理\n”, task_count, THREAD_COUNT);
// 创建线程
pthread_t threads[THREAD_COUNT];
ThreadData thread_data[THREAD_COUNT];
int files_per_thread = task_count / THREAD_COUNT;
int remainder = task_count % THREAD_COUNT;
for (int i = 0; i < THREAD_COUNT; i++) {
thread_data[i].tasks = tasks;
thread_data[i].task_count = task_count;
thread_data[i].old_str = old_str;
thread_data[i].new_str = new_str;
int start = i * files_per_thread + (i < remainder ? i : remainder);
int end = start + files_per_thread + (i < remainder ? 1 : 0);
thread_data[i].start_index = start;
thread_data[i].end_index = end;
pthread_create(&threads[i], NULL, process_file_batch, &thread_data[i]);
}
// 等待所有线程完成
for (int i = 0; i < THREAD_COUNT; i++) {
pthread_join(threads[i], NULL);
}
printf("所有文件处理完成!\n");
}
int main() {
// 创建测试文件
mkdir("test_parallel", 0755);
for (int i = 1; i <= 8; i++) {
char filename[256];
sprintf(filename, "test_parallel/file%d.txt", i);
FILE *f = fopen(filename, "w");
fprintf(f, "Original text in file %d\n", i);
fprintf(f, "Multiple lines with original content\n");
fclose(f);
}
// 并行处理
parallel_batch_replace("test_parallel", ".txt", "Original", "Modified");
return 0;
}
3.3 高级数据结构与文件处理
案例:构建文件索引系统
#include
#include
#include
#include
#include
// 文件信息结构
typedef struct FileInfo {
char *path;
size_t size;
time_t mtime;
struct FileInfo *next;
} FileInfo;
// 索引系统
typedef struct {
FileInfo **buckets;
int size;
int count;
} FileIndex;
// 哈希函数
unsigned int hash_string(const char *str, int table_size) {
unsigned int hash = 5381;
int c;
while ((c = *str++)) {
hash = ((hash << 5) + hash) + c; // hash * 33 + c
}
return hash % table_size;
}
// 创建索引
FileIndex* create_index(int size) {
FileIndex *index = malloc(sizeof(FileIndex));
index->size = size;
index->count = 0;
index->buckets = calloc(size, sizeof(FileInfo*));
return index;
}
// 添加文件到索引
void add_to_index(FileIndex *index, const char *path, size_t size, time_t mtime) {
unsigned int bucket = hash_string(path, index->size);
FileInfo *info = malloc(sizeof(FileInfo));
info->path = strdup(path);
info->size = size;
info->mtime = mtime;
info->next = index->buckets[bucket];
index->buckets[bucket] = info;
index->count++;
}
// 查找文件
FileInfo* find_in_index(FileIndex *index, const char *path) {
unsigned int bucket = hash_string(path, index->size);
FileInfo *current = index->buckets[bucket];
while (current) {
if (strcmp(current->path, path) == 0) {
return current;
}
current = current->next;
}
return NULL;
}
// 递归构建索引
void build_index_from_dir(FileIndex *index, const char *base_path) {
DIR *dir = opendir(base_path);
if (dir == NULL) return;
struct dirent *entry;
while ((entry = readdir(dir)) != NULL) {
if (strcmp(entry->d_name, “.”) == 0 || strcmp(entry->d_name, “..”) == 0) {
continue;
}
char full_path[1024];
snprintf(full_path, sizeof(full_path), “%s/%s”, base_path, entry->d_name);
struct stat sb;
if (stat(full_path, &sb) == 0) {
if (S_ISDIR(sb.st_mode)) {
build_index_from_dir(index, full_path);
} else if (S_ISREG(sb.st_mode)) {
add_to_index(index, full_path, sb.st_size, sb.st_mtime);
}
}
}
closedir(dir);
}
// 导出索引到文件
void export_index(const char *output_file, FileIndex *index) {
FILE *f = fopen(output_file, “w”);
if (f == NULL) {
perror(“无法创建索引文件”);
return;
}
fprintf(f, “File Index Export\n”);
fprintf(f, “=================\n”);
fprintf(f, “Total files: %d\n\n”, index->count);
for (int i = 0; i < index->size; i++) {
FileInfo *current = index->buckets[i];
while (current) {
struct tm *tm_info = localtime(¤t->mtime);
fprintf(f, “%s | Size: %zu bytes | Modified: %04d-%02d-%02d %02d:%02d:%02d\n”,
current->path,
current->size,
tm_info->tm_year + 1900,
tm_info->tm_mon + 1,
tm_info->tm_mday,
tm_info->tm_hour,
tm_info->tm_min,
tm_info->tm_sec);
current = current->next;
}
}
fclose(f);
}
// 释放索引
void free_index(FileIndex *index) {
for (int i = 0; i < index->size; i++) {
FileInfo *current = index->buckets[i];
while (current) {
FileInfo *next = current->next;
free(current->path);
free(current);
current = next;
}
}
free(index->buckets);
free(index);
}
int main() {
// 创建测试目录结构
mkdir(“test_index”, 0755);
mkdir(“test_index/subdir”, 0755);
FILE *f1 = fopen(“test_index/file1.txt”, “w”);
fprintf(f1, “Content 1”);
fclose(f1);
FILE *f2 = fopen(“test_index/subdir/file2.txt”, “w”);
fprintf(f2, “Content 2”);
fclose(f2);
// 构建索引
FileIndex *index = create_index(100);
build_index_from_dir(index, “test_index”);
// 导出索引
export_index(“file_index.txt”, index);
// 查找测试
FileInfo *info = find_in_index(index, “test_index/file1.txt”);
if (info) {
printf(“找到文件: %s (大小: %zu)\n”, info->path, info->size);
}
// 清理
free_index(index);
return 0;
}
第四部分:实战项目
4.1 日志分析器
#include
#include
#include
#include
#include
#define MAX_LINE 2048
#define MAX_IP 16
#define MAX_URL 256
#define MAX_USER_AGENT 512
typedef struct {
char ip[MAX_IP];
char url[MAX_URL];
char user_agent[MAX_USER_AGENT];
int status_code;
time_t timestamp;
} LogEntry;
// 解析Apache/Nginx日志
int parse_log_line(char *line, LogEntry *entry) {
// 简化版解析,实际应用需要更复杂的解析器
char *ip = strtok(line, ” “);
if (!ip) return 0;
strncpy(entry->ip, ip, MAX_IP – 1);
// 跳过一些字段
strtok(NULL, ” “);
strtok(NULL, ” “);
// 获取时间
char *time_str = strtok(NULL, “[“);
if (time_str) {
// 解析时间格式: 10/Oct/2023:13:55:36 +0000
struct tm tm;
strptime(time_str, “%d/%b/%Y:%H:%M:%S”, &tm);
entry->timestamp = mktime(&tm);
}
// 获取请求方法和URL
char *request = strtok(NULL, “\””);
if (request) {
char *method = strtok(request, ” “);
char *url = strtok(NULL, ” “);
if (url) {
strncpy(entry->url, url, MAX_URL – 1);
}
}
// 获取状态码
char *status = strtok(NULL, ” “);
if (status) {
entry->status_code = atoi(status);
}
// 获取User-Agent
char *ua = strtok(NULL, “\””);
if (ua) {
strncpy(entry->user_agent, ua, MAX_USER_AGENT – 1);
}
return 1;
}
// 日志分析统计
void analyze_logs(const char *filename) {
FILE *file = fopen(filename, “r”);
if (!file) {
perror(“无法打开日志文件”);
return;
}
char line[MAX_LINE];
LogEntry entry;
int total_requests = 0;
int error_count = 0;
int not_found_count = 0;
// 统计每个IP的访问次数
#define MAX_IPS 1000
struct {
char ip[MAX_IP];
int count;
} ip_stats[MAX_IPS];
int ip_count = 0;
// URL访问统计
struct {
char url[MAX_URL];
int count;
} url_stats[MAX_IPS];
int url_count = 0;
while (fgets(line, sizeof(line), file)) {
if (parse_log_line(line, &entry)) {
total_requests++;
// 统计状态码
if (entry.status_code >= 500) error_count++;
if (entry.status_code == 404) not_found_count++;
// IP统计
int found = 0;
for (int i = 0; i < ip_count; i++) {
if (strcmp(ip_stats[i].ip, entry.ip) == 0) {
ip_stats[i].count++;
found = 1;
break;
}
}
if (!found && ip_count < MAX_IPS) {
strncpy(ip_stats[ip_count].ip, entry.ip, MAX_IP);
ip_stats[ip_count].count = 1;
ip_count++;
}
// URL统计
found = 0;
for (int i = 0; i < url_count; i++) {
if (strcmp(url_stats[i].url, entry.url) == 0) {
url_stats[i].count++;
found = 1;
break;
}
}
if (!found && url_count < MAX_IPS) {
strncpy(url_stats[url_count].url, entry.url, MAX_URL);
url_stats[url_count].count = 1;
url_count++;
}
}
}
fclose(file);
// 输出报告
printf("=== 日志分析报告 ===\n");
printf("总请求数: %d\n", total_requests);
printf("错误请求(5xx): %d\n", error_count);
printf("未找到(404): %d\n", not_found_count);
printf("错误率: %.2f%%\n", (error_count * 100.0) / total_requests);
// Top 5 IP
printf("\nTop 5 访问IP:\n");
for (int i = 0; i < 5 && i < ip_count; i++) {
int max_idx = 0;
for (int j = 1; j < ip_count; j++) {
if (ip_stats[j].count > ip_stats[max_idx].count) {
max_idx = j;
}
}
if (ip_stats[max_idx].count > 0) {
printf(” %s: %d 次\n”, ip_stats[max_idx].ip, ip_stats[max_idx].count);
ip_stats[max_idx].count = 0; // 标记为已输出
}
}
// Top 5 URL
printf(“\nTop 5 访问URL:\n”);
for (int i = 0; i < 5 && i < url_count; i++) {
int max_idx = 0;
for (int j = 1; j < url_count; j++) {
if (url_stats[j].count > url_stats[max_idx].count) {
max_idx = j;
}
}
if (url_stats[max_idx].count > 0) {
printf(” %s: %d 次\n”, url_stats[max_idx].url, url_stats[max_idx].count);
url_stats[max_idx].count = 0;
}
}
}
int main() {
// 创建测试日志
FILE *log = fopen(“access.log”, “w”);
fprintf(log, “192.168.1.1 – – [10/Oct/2023:13:55:36 +0000] \”GET /index.html HTTP/1.1\” 200 1234 \”-\” \”Mozilla/5.0\”\n”);
fprintf(log, “192.168.1.2 – – [10/Oct/2023:13:55:37 +0000] \”GET /about.html HTTP/1.1\” 200 567 \”-\” \”Mozilla/5.0\”\n”);
fprintf(log, “192.168.1.1 – – [10/Oct/2023:13:55:38 +0000] \”GET /contact.html HTTP/1.1\” 404 0 \”-\” \”Mozilla/5.0\”\n”);
fprintf(log, “192.168.1.3 – – [10/Oct/2023:13:55:39 +0000] \”GET /index.html HTTP/1.1\” 500 0 \”-\” \”Mozilla/5.0\”\n”);
fprintf(log, “192.168.1.1 – – [10/Oct/2023:13:55:40 +0000] \”GET /index.html HTTP/1.1\” 200 1234 \”-\” \”Mozilla/5.0\”\n”);
fclose(log);
analyze_logs(“access.log”);
return 0;
}
4.2 数据清洗工具
#include
#include
#include
#include
#define MAX_LINE 8192
// 数据清洗函数
void clean_data_file(const char *input_file, const char *output_file) {
FILE *in = fopen(input_file, “r”);
FILE *out = fopen(output_file, “w”);
if (!in || !out) {
perror(“文件打开失败”);
if (in) fclose(in);
if (out) fclose(out);
return;
}
char line[MAX_LINE];
int line_num = 0;
int cleaned_count = 0;
while (fgets(line, sizeof(line), in)) {
line_num++;
char cleaned[MAX_LINE];
char *src = line;
char *dst = cleaned;
int changed = 0;
// 1. 去除行首尾空白
while (isspace((unsigned char)*src)) {
src++;
changed = 1;
}
// 2. 去除行尾换行符和空白
char *end = src + strlen(src) – 1;
while (end > src && isspace((unsigned char)*end)) {
end–;
changed = 1;
}
*(end + 1) = ‘\0’;
// 3. 去除行内多余空白(将多个空白合并为一个空格)
int in_space = 0;
while (*src) {
if (isspace((unsigned char)*src)) {
if (!in_space) {
*dst++ = ‘ ‘;
in_space = 1;
changed = 1;
}
} else {
*dst++ = *src;
in_space = 0;
}
src++;
}
*dst = ‘\0’;
// 4. 去除不可打印字符
dst = cleaned;
while (*dst) {
if (!isprint((unsigned char)*dst) && *dst != ‘\t’) {
*dst = ‘ ‘;
changed = 1;
}
dst++;
}
// 写入清洗后的数据
if (strlen(cleaned) > 0) {
fprintf(out, “%s\n”, cleaned);
if (changed) cleaned_count++;
} else {
// 空行,可以选择跳过或保留
fprintf(out, “%s”, cleaned);
}
}
printf(“数据清洗完成:\n”);
printf(” 处理行数: %d\n”, line_num);
printf(” 清洗行数: %d\n”, cleaned_count);
printf(” 输出文件: %s\n”, output_file);
fclose(in);
fclose(out);
}
// CSV数据清洗和验证
void clean_csv_file(const char *input_file, const char *output_file) {
FILE *in = fopen(input_file, “r”);
FILE *out = fopen(output_file, “w”);
if (!in || !out) {
perror(“文件打开失败”);
if (in) fclose(in);
if (out) fclose(out);
return;
}
char line[MAX_LINE];
int line_num = 0;
int invalid_lines = 0;
while (fgets(line, sizeof(line), in)) {
line_num++;
// 去除换行符
line[strcspn(line, “\n”)] = 0;
// 简单的CSV验证:检查字段数量
int field_count = 1;
char *p = line;
while (*p) {
if (*p == ‘,’) field_count++;
p++;
}
// 假设期望3个字段
if (field_count == 3) {
// 清洗每个字段
char *fields[3];
int field_idx = 0;
char *token = strtok(line, “,”);
while (token && field_idx < 3) {
// 去除空白和引号
while (isspace((unsigned char)*token)) token++;
char *end = token + strlen(token) - 1;
while (end > token && isspace((unsigned char)*end)) end–;
*(end + 1) = ‘\0’;
if (*token == ‘”‘ && *(end) == ‘”‘) {
token++;
*end = ‘\0’;
}
fields[field_idx++] = token;
token = strtok(NULL, “,”);
}
// 写入清洗后的CSV
fprintf(out, “%s,%s,%s\n”, fields[0], fields[1], fields[2]);
} else {
printf(“警告: 第%d行格式无效 (字段数: %d)\n”, line_num, field_count);
invalid_lines++;
}
}
printf(“\nCSV清洗完成:\n”);
printf(” 总行数: %d\n”, line_num);
printf(” 无效行数: %d\n”, invalid_lines);
printf(” 有效行数: %d\n”, line_num – invalid_lines);
fclose(in);
fclose(out);
}
int main() {
// 创建测试数据
FILE *f = fopen(“dirty_data.txt”, “w”);
fprintf(f, ” Name1 , Age1 , City1 \n”);
fprintf(f, “Name2,Age2,City2\n”);
fprintf(f, ” Name3 , Age3 , City3 \n”);
fprintf(f, “Name4 ,Age4,City4\n”);
fclose(f);
clean_data_file(“dirty_data.txt”, “clean_data.txt”);
// 创建测试CSV
FILE *csv = fopen(“dirty.csv”, “w”);
fprintf(csv, ” John , 25 , \”New York\” \n”);
fprintf(csv, “Alice,30,London\n”);
fprintf(csv, ” Bob , 35 , \”San Francisco\” \n”);
fclose(csv);
clean_csv_file(“dirty.csv”, “clean.csv”);
return 0;
}
第五部分:性能优化与最佳实践
5.1 缓冲区管理优化
#include
#include
#include
// 自定义缓冲区结构
typedef struct {
char *data;
size_t size;
size_t capacity;
size_t position;
} Buffer;
// 初始化缓冲区
Buffer* buffer_create(size_t initial_capacity) {
Buffer *buf = malloc(sizeof(Buffer));
buf->data = malloc(initial_capacity);
buf->size = 0;
buf->capacity = initial_capacity;
buf->position = 0;
return buf;
}
// 扩展缓冲区
void buffer_expand(Buffer *buf, size_t additional) {
size_t required = buf->size + additional;
if (required <= buf->capacity) return;
size_t new_capacity = buf->capacity * 2;
while (new_capacity < required) new_capacity *= 2;
char *new_data = realloc(buf->data, new_capacity);
if (new_data) {
buf->data = new_data;
buf->capacity = new_capacity;
}
}
// 写入缓冲区
void buffer_write(Buffer *buf, const void *data, size_t len) {
buffer_expand(buf, len);
memcpy(buf->data + buf->size, data, len);
buf->size += len;
}
// 格式化写入
void buffer_printf(Buffer *buf, const char *format, …) {
va_list args;
va_start(args, format);
// 预估所需空间
int needed = vsnprintf(NULL, 0, format, args);
va_end(args);
if (needed > 0) {
buffer_expand(buf, needed + 1);
va_start(args, format);
vsnprintf(buf->data + buf->size, needed + 1, format, args);
buf->size += needed;
va_end(args);
}
}
// 批量写入文件
size_t buffer_flush_to_file(Buffer *buf, FILE *file) {
size_t written = fwrite(buf->data, 1, buf->size, file);
if (written == buf->size) {
buf->size = 0;
} else {
// 移动剩余数据到开头
memmove(buf->data, buf->data + written, buf->size – written);
buf->size -= written;
}
return written;
}
// 释放缓冲区
void buffer_free(Buffer *buf) {
if (buf) {
free(buf->data);
free(buf);
}
}
// 使用缓冲区进行高效文件处理
void process_with_buffer(const char *input_file, const char *output_file) {
FILE *in = fopen(input_file, “r”);
FILE *out = fopen(output_file, “w”);
if (!in || !out) {
perror(“文件打开失败”);
return;
}
Buffer *buf = buffer_create(65536); // 64KB缓冲区
char line[4096];
int line_count = 0;
while (fgets(line, sizeof(line), in)) {
// 处理行(示例:添加行号)
buffer_printf(buf, “%06d: %s”, ++line_count, line);
// 当缓冲区较大时刷新到文件
if (buf->size > 60000) {
buffer_flush_to_file(buf, out);
}
}
// 刷新剩余数据
if (buf->size > 0) {
buffer_flush_to_file(buf, out);
}
buffer_free(buf);
fclose(in);
fclose(out);
}
5.2 错误处理与恢复机制
#include
#include
#include
#include
#include
// 错误处理上下文
typedef struct {
jmp_buf jump_buffer;
char error_message[1024];
int error_code;
} ErrorContext;
// 全局错误上下文(简化版,实际应用中应通过参数传递)
static ErrorContext global_error_ctx;
// 设置错误
void set_error(ErrorContext *ctx, int code, const char *msg) {
ctx->error_code = code;
strncpy(ctx->error_message, msg, sizeof(ctx->error_message) – 1);
ctx->error_message[sizeof(ctx->error_message) – 1] = ‘\0’;
}
// 带错误处理的文件操作
#define TRY if (setjmp(global_error_ctx.jump_buffer) == 0)
#define CATCH else
#define THROW(code, msg) { \
set_error(&global_error_ctx, code, msg); \
longjmp(global_error_ctx.jump_buffer, 1); \
}
// 安全的文件复制(带错误处理)
int safe_copy_with_recovery(const char *source, const char *dest) {
FILE *src = NULL, *dst = NULL;
char *buffer = NULL;
const size_t buffer_size = 8192;
int result = -1;
TRY {
src = fopen(source, “rb”);
if (!src) {
THROW(1, “无法打开源文件”);
}
dst = fopen(dest, “wb”);
if (!dst) {
THROW(2, “无法创建目标文件”);
}
buffer = malloc(buffer_size);
if (!buffer) {
THROW(3, “内存分配失败”);
}
size_t bytes;
while ((bytes = fread(buffer, 1, buffer_size, src)) > 0) {
if (fwrite(buffer, 1, bytes, dst) != bytes) {
THROW(4, “写入不完整”);
}
}
if (ferror(src)) {
THROW(5, “读取错误”);
}
result = 0; // 成功
}
CATCH {
fprintf(stderr, “错误 %d: %s\n”, global_error_ctx.error_code,
global_error_ctx.error_message);
// 清理部分创建的资源
if (dst) {
fclose(dst);
remove(dest); // 删除不完整的输出文件
}
}
// 清理资源
if (src) fclose(src);
if (buffer) free(buffer);
return result;
}
第六部分:调试与测试
6.1 文件处理单元测试框架
#include
#include
#include
#include
// 测试框架宏
#define TEST(name) void test_##name(); \
printf(“运行测试: %s\n”, #name); \
test_##name(); \
printf(” ✓ 通过\n”);
#define ASSERT_EQ(expected, actual) \
if ((expected) != (actual)) { \
fprintf(stderr, ” ✗ 失败: 期望 %d, 实际 %d\n”, (int)(expected), (int)(actual)); \
exit(1); \
}
#define ASSERT_STR_EQ(expected, actual) \
if (strcmp((expected), (actual)) != 0) { \
fprintf(stderr, ” ✗ 失败: 期望 ‘%s’, 实际 ‘%s’\n”, (expected), (actual)); \
exit(1); \
}
// 测试辅助函数
void create_test_file(const char *name, const char *content) {
FILE *f = fopen(name, “w”);
if (f) {
fprintf(f, “%s”, content);
fclose(f);
}
}
// 测试CSV解析
void test_csv_parser() {
create_test_file(“test.csv”, “Name,Age,City\nAlice,25,NY\nBob,30,LA\n”);
FILE *f = fopen(“test.csv”, “r”);
char line[256];
// 读取标题
fgets(line, sizeof(line), f);
ASSERT_STR_EQ(“Name,Age,City\n”, line);
// 读取第一行数据
fgets(line, sizeof(line), f);
ASSERT_STR_EQ(“Alice,25,NY\n”, line);
fclose(f);
}
// 测试文件复制
void test_file_copy() {
create_test_file(“source.txt”, “Test content”);
int result = safe_file_copy(“source.txt”, “dest.txt”);
ASSERT_EQ(0, result);
// 验证内容
FILE *f = fopen(“dest.txt”, “r”);
char content[100];
fgets(content, sizeof(content), f);
fclose(f);
ASSERT_STR_EQ(“Test content”, content);
}
// 运行所有测试
void run_all_tests() {
printf(“=== 开始测试 ===\n”);
TEST(csv_parser);
TEST(file_copy);
printf(“=== 所有测试通过 ===\n”);
}
int main() {
run_all_tests();
return 0;
}
第七部分:跨平台注意事项
7.1 路径分隔符处理
#include
#include
// 跨平台路径处理
#ifdef _WIN32
#define PATH_SEP ‘\\’
#define PATH_SEP_STR “\\”
#else
#define PATH_SEP ‘/’
#define PATH_SEP_STR “/”
#endif
// 跨平台路径构建
void build_path(char *result, size_t result_size,
const char *dir, const char *file) {
#ifdef _WIN32
// Windows路径处理
snprintf(result, result_size, “%s\\%s”, dir, file);
#else
// Unix路径处理
snprintf(result, result_size, “%s/%s”, dir, file);
#endif
}
// 路径标准化
void normalize_path(char *path) {
#ifdef _WIN32
// 将/转换为\
for (size_t i = 0; path[i]; i++) {
if (path[i] == ‘/’) path[i] = ‘\\’;
}
#else
// 将\转换为/
for (size_t i = 0; path[i]; i++) {
if (path[i] == ‘\\’) path[i] = ‘/’;
}
#endif
}
总结
通过本文的学习,你已经掌握了C语言文本批处理的核心技术:
基础文件操作
:熟练使用fopen、fread、fwrite等函数
批量处理技术
:目录遍历、批量重命名、内容替换
高级技巧
:内存映射、并行处理、数据结构应用
实战项目
:日志分析、数据清洗等完整案例
性能优化
:缓冲区管理、错误处理
测试与调试
:单元测试框架
跨平台开发
:路径处理等注意事项
关键要点回顾
始终检查返回值
:所有文件操作都要检查是否成功
资源管理
:及时关闭文件,避免内存泄漏
错误处理
:使用perror()或strerror(errno)获取详细错误信息
性能考虑
:大文件使用内存映射,批量操作使用缓冲区
代码可维护性
:模块化设计,充分注释
进一步学习建议
学习更多C标准库函数(如fseek、ftell、rewind等)
研究操作系统特定API(如Windows的CreateFile)
探索更复杂的数据结构(B树、哈希表)用于文件索引
学习多进程文件处理(fork、进程间通信)
了解文件系统原理和性能调优
通过这些技术,你可以构建高效、可靠的文本批处理系统,解决各种实际问题。记住,优秀的C程序员不仅要写出能工作的代码,还要写出健壮、高效、可维护的代码。