Search code examples
clinuxioposixsystem-calls

How to read line by line using system call in C


In my program, I can currently read char by char a file with given name "fichier1.txt", but what I'm looking for is to store a line(line char pointer here) and then display it that way :

-ligne 1 : content line 1

-line 2 : content line 2

-ect...

I've tried to store char by char but since it's a pointer and I'm yet that much familiar with pointers I'm not able to store a line and then reuse the pointer to store the char of the next line.

I have to say that it's part of a school projet and I have to use POSIX standard.

#include<stdio.h>
#include<stdlib.h>
#include<errno.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/wait.h>
#include <pthread.h>
#include<string.h>
#include <sys/stat.h>
#include <fcntl.h>

int main(){
    int read_fd, write_fd;
    off_t offset = 0;
    char lu;
    struct stat statFd;
    char *fichier = "fichier1.txt";


    read_fd = open(fichier,O_RDONLY);
    stat(fichier, &statFd);

    if(read_fd == -1){
        perror("open");
        exit(EXIT_FAILURE);
    }

    int i = 0;
    char * line; // variable to store line

    while(lseek(read_fd,offset, SEEK_SET) < statFd.st_size)
    {
        if(read(read_fd, &lu, 1) != -1)
        {
            printf("%c",lu);
            offset++;

        } else {
            perror("READ\n");
            close(read_fd);
            close(write_fd);
            exit(EXIT_FAILURE);
        }
    }

    return 0;
}



I'd like to use open() function and not fopen()


Solution

  • Since you are able to read character after character from the file, the logic in while loop will be used to store an entire line (up to 199 characters, you can increase it though) at once in an array & then display it:

    #include<stdio.h>
    #include<string.h>
    #include<stdlib.h>
    
    
    
    int main(void)
    {
        FILE *fptr=fopen( "fichier1.txt","r");
        int  i;
        char arr[200];     //THIS ARRAY WILL HOLD THE CONTENTS OF A LINE TEMPORARILY UNTIL IT IS PRINTED                       
        int temp_index=0,line_number=1;;
        memset(arr,'\0',sizeof(arr));
    
        while((i=getc(fptr))!=EOF)                         
        {
            if(i!='\n')                                
            {
                arr[temp_index++]=i; 
            }   
            if(i=='\n')
            {
                printf(line %d: %s\n",line_number++,arr);
                temp_index=0;
                memset(arr,'\0',sizeof(arr));
            } 
        }
        return 0;
    }