C语言使用open()和read()打印文件前10行的问题咨询
问题原因
你的代码存在3个核心逻辑错误,导致无法按行计数停止:
- 运算符优先级错误:
=的优先级低于&&,你写的res = read(fd, c, 1) && max < 10等效于res = (read(fd, c, 1) && (max < 10)),res只会被赋值为逻辑运算的结果0或1,完全拿不到read的真实返回值 - 字符索引逻辑错误:你每次调用
read只读1个字节,存在c[0]的位置,你却操作c[res]写入终止符、判断换行,完全读不到刚读取的字符 - 缺少错误退出逻辑:
open/read报错后没有终止程序,会继续执行后续无效逻辑
修正后代码
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <errno.h> int main(){ int fd = open("a.txt", O_RDONLY); if(fd < 0){ printf("Error: %d\n", errno); perror(""); return EXIT_FAILURE; } char c; ssize_t res; int line_count = 0; // 加括号保证赋值优先执行,先拿read返回值再做逻辑判断 while(line_count < 10 && (res = read(fd, &c, 1)) > 0){ if(res < 0){ printf("Error: %d\n", errno); perror(""); close(fd); return EXIT_FAILURE; } putchar(c); if(c == '\n'){ line_count++; } } close(fd); return EXIT_SUCCESS; }
调整说明
- 给
res = read(...)加括号,保证先拿到读取结果再做逻辑判断 - 简化缓冲区,直接用单个char变量存储读取的1字节,避免索引错误
- 换行计数逻辑调整为直接判断读取到的字符,读取到换行立刻计数+1,满10行直接退出循环
- 补充所有错误分支的退出逻辑,避免资源泄漏和无效执行
内容的提问来源于stack exchange,提问作者Boisbois2
相关产品推荐
相关产品推荐

