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
相关产品推荐
相关产品推荐

