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

C语言如何根据输入的行号打印文本文件中对应行的内容

实现修改思路

  • 新增用户输入逻辑,接收需要查询的目标行号
  • 新增行计数器,遍历文件时逐行累加计数
  • 匹配到目标行号时输出对应行内容,提前终止文件遍历提升效率
  • 新增异常判断逻辑:遍历完文件仍未匹配到目标行时,提示行号不存在
  • 修正原代码笔误:将不存在的print函数改为标准库printf,删除不需要的分隔符输出逻辑,同时修正多余换行的问题(fgets读取的行内容自带换行符,无需额外加\n)

修改后完整代码

#include <stdio.h>
#include <stdlib.h>

int main() {
    FILE *fp;
    fp = fopen("sample.txt", "r");
    if (fp == NULL) {
        perror("Unable to open the file");
        exit(1);
    }
    char buf[256];
    int target_line, current_line = 0;

    // 接收用户输入的行号
    printf("Enter the line number:");
    scanf("%d", &target_line);

    // 遍历文件逐行匹配
    while (fgets(buf, sizeof(buf), fp) != NULL) {
        current_line++;
        if (current_line == target_line) {
            printf("%s", buf);
            break;
        }
    }

    // 处理行号不存在的异常场景
    if (current_line < target_line) {
        printf("输入的行号不存在,文件共有%d行\n", current_line);
    }

    fclose(fp);
    return 0;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.17 19:09:03