C语言文件编辑编程:替换首个空文件名字段并保持原格式输出
问题描述
需要编写C程序读取input.txt中的文件条目列表,生成output.txt,规则如下:
- 仅将索引为
[0]的第一条记录中的文件名字段从空字符串""替换为"Testfile" - 其余所有内容、排版对齐方式完全和输入文件一致
输入输出示例
输入文件input.txt内容
File entry structures: [0] "" 0 -1 [1] "" 0 -1 [2] "" 0 -1 [3] "" 0 -1 [4] "" 0 -1
预期输出文件output.txt内容
File entry structures: [0] "Testfile" 0 -1 [1] "" 0 -1 [2] "" 0 -1 [3] "" 0 -1 [4] "" 0 -1
现有代码框架
#include <stdio.h> int main() { FILE *input_file, *output_file; int size, fblock; char index[81]; char name[81]; input_file = fopen("input.txt", "r"); output_file = fopen("output.txt", "w"); // ignore "File entry structures:" line when reading/writing while (fscanf(input_file, "%80s %80s %d %d", index, name, &size, &fblock) == 4) { fprintf(output_file, ... ); }
当前问题:不清楚fprintf的格式参数如何编写,才能保证输出格式和输入完全对齐,同时完成首条记录的字段替换。
实现方案
核心处理逻辑分三点:
- 先把输入文件第一行表头
File entry structures:原样读取并写入输出文件,避免表头丢失 - 增加首条记录标记,遍历条目时如果是第一条
[0]记录,将文件名替换为带双引号的"Testfile",其余条目直接使用读取到的原文件名字段 fprintf使用固定间隔的格式串,完全匹配原文件的空格排版:文件名后固定2个空格,size字段后固定7个空格,和原格式对齐
完整可运行代码
#include <stdio.h> int main() { FILE *input_file, *output_file; int size, fblock; char index[81]; char name[81]; char line_buf[256]; int is_first_entry = 1; input_file = fopen("input.txt", "r"); output_file = fopen("output.txt", "w"); // 读取并原样写入表头行 fgets(line_buf, sizeof(line_buf), input_file); fputs(line_buf, output_file); while (fscanf(input_file, "%80s %80s %d %d", index, name, &size, &fblock) == 4) { char* output_name = name; // 第一条记录替换文件名 if (is_first_entry) { output_name = "\"Testfile\""; is_first_entry = 0; } // 格式串完全匹配原排版,字段间空格数和原文件完全一致 fprintf(output_file, "%s %s %d %d\n", index, output_name, size, fblock); } fclose(input_file); fclose(output_file); return 0; }
格式说明
fprintf的格式串"%s %s %d %d\n"完全对齐原文件排版:
- 第一个
%s输出索引值(如[0]),后接1个空格 - 第二个
%s输出文件名,后接2个空格 - 第一个
%d输出size值,后接7个空格 - 第二个
%d输出fblock值,后接换行符
运行后生成的output.txt和预期格式完全一致,无排版错位。
内容的提问来源于stack exchange,提问作者Heskinammo
相关产品推荐
相关产品推荐

