如何使用C中的系统调用读取文件行直到结束?

如何使用C中的系统调用读取文件行直到结束?,c,io,C,Io,我试图通过比较当前读取的字符与\n(行尾符号)逐行读取文件。该行的字符存储在缓冲区中 我不知道如何同时处理缓冲区,在缓冲区中保留当前行和带有行尾字符的支票。这就是我使用indexCurrentSymbol的目的,它始终是缓冲区的最后一个符号,并查看它是否是\n 请不要告诉我,我应该通过基本的系统调用来实现这一点(所以没有读完整行的库函数) 输入是 Animal, Size Dog, Big Duck, Small Mouse, Tiny Horse, Huge 我忽略了所有错误检查文件,这些文

我试图通过比较当前读取的字符与
\n
(行尾符号)逐行读取文件。该行的字符存储在缓冲区中

我不知道如何同时处理缓冲区,在缓冲区中保留当前行和带有行尾字符的支票。这就是我使用
indexCurrentSymbol
的目的,它始终是缓冲区的最后一个符号,并查看它是否是
\n

请不要告诉我,我应该通过基本的系统调用来实现这一点(所以没有读完整行的库函数)

输入是

Animal, Size
Dog, Big
Duck, Small
Mouse, Tiny
Horse, Huge
我忽略了所有错误检查文件,这些文件可能不是为了能够专注于任务而提供的

#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>

int main(int argc, char *argv[]) { 

    // Open file to read line.
    int input = open(argv[1], O_RDONLY);
    char buf[100];
    int read_bytes = read(input, &buf, 1); 
    int indexCurrentSymbol = 0;
    while (buf[indexCurrentSymbol] != '\n') {
        // read(input, buf, 1);    // Correction based on comment.
        read(input, &buf[indexCurrentSymbol], 1);
        indexCurrentSymbol++;
    }   

    close(input);
    return 0;
}
#包括
#包括
#包括
#包括
#包括
#包括
intmain(intargc,char*argv[]){
//打开文件以读取行。
int输入=打开(argv[1],仅限Ordu);
char-buf[100];
int read_bytes=read(输入,&buf,1);
int indexCurrentSymbol=0;
while(buf[indexCurrentSymbol]!='\n'){
//读取(输入,buf,1);//根据注释进行更正。
读取(输入,&buf[indexCurrentSymbol],1);
indexCurrentSymbol++;
}   
关闭(输入);
返回0;
}

这是一个修改过的程序版本,允许读取整个文件 (请注意,错误处理是不够的,并且没有检查
buf
最大大小):

我得到:

$ ./tread tread.dat
current buf=
Animal, Size

current buf=
Animal, Size
Dog, Big

current buf=
Animal, Size
Dog, Big
Duck, Small

current buf=
Animal, Size
Dog, Big
Duck, Small
Mouse, Tiny

current buf=
Animal, Size
Dog, Big
Duck, Small
Mouse, Tiny
Horse, Huge

final buf=
Animal, Size
Dog, Big
Duck, Small
Mouse, Tiny
Horse, Huge

你为什么一直覆盖缓冲区中的第一个字符?嗯,你的权利。现在,我使用
indexCurrentSymbol
计数器增加缓冲区中的写入位置。我想这更有意义,但仍然不能解决问题。
$ cat tread.dat
Animal, Size
Dog, Big
Duck, Small
Mouse, Tiny
Horse, Huge
$ ./tread tread.dat
current buf=
Animal, Size

current buf=
Animal, Size
Dog, Big

current buf=
Animal, Size
Dog, Big
Duck, Small

current buf=
Animal, Size
Dog, Big
Duck, Small
Mouse, Tiny

current buf=
Animal, Size
Dog, Big
Duck, Small
Mouse, Tiny
Horse, Huge

final buf=
Animal, Size
Dog, Big
Duck, Small
Mouse, Tiny
Horse, Huge