TMOTTM
TMOTTM

Reputation: 3391

How to read line of file until end using system calls in C?

I'm trying to read a file line by line by comparing the currently read character with \n (end of line symbol). The characters of that line are stored in a buffer.

I'm confused how to handle at the same time the buffer, where I keep the current line and the check with the end of line character. That's what I use the indexCurrentSymbol for, to always the the last symbol of the buffer and see if it's \n.

Please not that I'm supposed to achieve this with basic system calls (so no library functions that read a full line).

The input is

Animal, Size
Dog, Big
Duck, Small
Mouse, Tiny
Horse, Huge

I'm ignoring all error checks for files that might not be available on purpose to be able to focus on the task.

#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;
}

Upvotes: 0

Views: 1640

Answers (1)

pifor
pifor

Reputation: 7892

Here is a modified program version that allows to read the whole file (note that error processing is not enough and there is no check on buf maximum size):

#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[]) { 


    char buf[100];
    int indexCurrentSymbol = 0;
    int read_bytes;
    int line_read=0;
    int file_read=0;

    // Open file to read line.
    int input = open(argv[1], O_RDONLY);
    if (input < 0) 
    perror("open");

    buf[0] = '\0';
    while (file_read == 0) {

        read_bytes = read(input, &buf[indexCurrentSymbol], 1);
        if (read_bytes == -1) 
           perror("read while: -1");
        if (read_bytes == 0) 
            file_read = 1;

        if (buf[indexCurrentSymbol] == '\n')
             printf("current buf=\n%s\n", buf);

        indexCurrentSymbol++;
    }   

    printf("final buf=\n%s\n", buf);
    close(input);
    return 0;
}

With:

$ cat tread.dat
Animal, Size
Dog, Big
Duck, Small
Mouse, Tiny
Horse, Huge

I get:

$ ./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

Upvotes: 1

Related Questions