【发布时间】:2021-12-19 17:34:36
【问题描述】:
我正在尝试使用函数 open() 和 read() 打印 txt 文件的前 10 行。到目前为止,我已经设法打印了整个文件,但是当我到达第 10 行的末尾时,我遇到了停止代码的问题。我该怎么办?
#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("");
}
char *c = (char*)calloc(100, sizeof(char));
ssize_t res;
int max = 0;
while(res = read(fd, c, 1) && max < 10){
if(res < 0){
printf("Error: %d\n", errno);
perror("");
}
c[res] = '\0';
if(c[res] == '\n'){
max++;
}
printf("%s", c);
}
close(fd);
return 0;
}
【问题讨论】:
-
简短的回答是使用流和面向行的输入函数,如
fopen()和fgets()。 -
在该行中: if(c[res] == '\n'){ c[res] 永远不会是 '\n' 因为你刚刚在上一行中设置了 '\0' .
-
@SergioJ.Batarce 更不用说如果
res是读取的字节数,那么c[res]是该数据之外的一个字节;读取的字节是c[0]到c[res-1]。哈哈。