文件操作示例
综合文件操作知识,实现常见的文件处理任务:复制文件、合并文件、统计信息、配置文件读写等。这些示例展示了文件操作的实际应用模式。
文件复制
#include <stdio.h>
int copy_file(const char *src, const char *dst)
{
FILE *in = fopen(src, "rb");
if (in == NULL) return -1;
FILE *out = fopen(dst, "wb");
if (out == NULL) {
fclose(in);
return -1;
}
char buffer[4096];
size_t n;
while ((n = fread(buffer, 1, sizeof(buffer), in)) > 0) {
fwrite(buffer, 1, n, out);
}
fclose(in);
fclose(out);
return 0;
}
逐行处理
void process_lines(const char *filename)
{
FILE *fp = fopen(filename, "r");
if (fp == NULL) return;
char line[256];
int line_num = 0;
while (fgets(line, sizeof(line), fp) != NULL) {
line_num++;
/* 去掉换行符 */
line[strcspn(line, "\n")] = '\0';
printf("Line %d: %s\n", line_num, line);
}
fclose(fp);
}
配置文件读写
/* 简单 key=value 格式 */
void read_config(const char *filename)
{
FILE *fp = fopen(filename, "r");
if (fp == NULL) return;
char line[256];
while (fgets(line, sizeof(line), fp) != NULL) {
char key[128], value[128];
if (sscanf(line, "%127s = %127s", key, value) == 2) {
printf("%s = %s\n", key, value);
}
}
fclose(fp);
}
二进制数据保存
struct Record {
int id;
char name[32];
double score;
};
void save_records(const char *filename, struct Record *records, int n)
{
FILE *fp = fopen(filename, "wb");
if (fp == NULL) return;
/* 写入数量 */
fwrite(&n, sizeof(int), 1, fp);
/* 写入记录 */
fwrite(records, sizeof(struct Record), n, fp);
fclose(fp);
}
int load_records(const char *filename, struct Record *records, int max_n)
{
FILE *fp = fopen(filename, "rb");
if (fp == NULL) return -1;
int n;
fread(&n, sizeof(int), 1, fp);
if (n > max_n) n = max_n;
fread(records, sizeof(struct Record), n, fp);
fclose(fp);
return n;
}
最佳实践
- 复制文件用缓冲区提高效率
- 文本处理注意换行符和缓冲区大小
- 二进制数据考虑字节序和版本兼容
- 配置文件用简单格式,复杂格式用专用库
- 始终检查文件操作返回值