You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C语言实现文件按行逆序输出至文件及控制台并修复空行问题

改进后的C语言代码实现

以下代码解决了多余空行问题,同时实现了文件写入、各项统计功能:

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

#define MAX_LINE_LEN 1024

int main() {
    FILE *src_file = fopen("mfile.txt", "r");
    FILE *dest_file = fopen("file2.txt", "w");
    
    if (!src_file || !dest_file) {
        perror("文件打开失败");
        return 1;
    }

    char line[MAX_LINE_LEN];
    int line_count = 0;
    int char_count = 0;
    int word_count = 0;
    int in_word = 0;

    // 逐行处理文件
    while (fgets(line, MAX_LINE_LEN, src_file) != NULL) {
        line_count++;
        int line_len = strlen(line);
        
        // 统计字符数:包含换行符在内的所有字符
        char_count += line_len;

        // 统计单词数:以空白字符为分隔判定单词边界
        for (int i = 0; i < line_len; i++) {
            if (isspace(line[i])) {
                in_word = 0;
            } else if (!in_word) {
                in_word = 1;
                word_count++;
            }
        }

        // 输出原内容到控制台,避免多余空行
        printf("%s", line);

        // 反转当前行:单独处理换行符,避免反转后换行符位置错误
        int start = 0;
        int end = line_len - 1;
        if (line[end] == '\n') {
            end--;
        }
        while (start < end) {
            char temp = line[start];
            line[start] = line[end];
            line[end] = temp;
            start++;
            end--;
        }
        // 补回换行符,保证行结构一致
        if (line_len > 0 && line[line_len - 1] != '\n') {
            line[line_len] = '\n';
            line_len++;
        }

        // 将反转后的行写入目标文件
        fputs(line, dest_file);
    }

    // 计算每行平均字符数,处理空文件的边界情况
    double avg_chars_per_line = (line_count > 0) ? (double)char_count / line_count : 0.0;

    // 输出统计结果
    printf("\n=== 统计结果 ===\n");
    printf("总行数:%d\n", line_count);
    printf("总单词数:%d\n", word_count);
    printf("总字符数:%d\n", char_count);
    printf("每行平均字符数:%.2f\n", avg_chars_per_line);

    fclose(src_file);
    fclose(dest_file);
    return 0;
}

关键改进点说明

  • 消除多余空行:直接用fgets读取包含换行符的完整行,通过printf("%s", line)输出,避免额外添加换行;反转行时单独保留换行符位置,保证写入新文件的行格式正确。
  • 实现文件写入:打开file2.txt后,将反转后的每行通过fputs写入,保持原文件的行结构。
  • 完善统计逻辑:
    • 行数:每成功读取一行计数加1。
    • 字符数:累加每行的实际长度(包含换行符)。
    • 单词数:通过空白字符切换"在单词中"的状态,准确统计单词数量。
    • 每行平均字符数:用浮点型计算,避免整数除法丢失精度,同时处理空文件的边界情况。
  • 异常处理:添加文件打开失败的报错逻辑,避免程序崩溃。

内容的提问来源于stack exchange,提问作者Vasia Pupkin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 01:25:27