Printing a number of lines using low level i/o in C

89 Views Asked by At

I am new to C and I'm trying to get familiar with low level I/O such as read() and write(), and I'm trying to print lines to standard out from a file using it, but I can't figure out how to do it while still only using low level functions.

Heres what I have so far, any suggestions would be super appreciated

enter image description here

I tried to iterate through the char array I have and checking for '\n' but it doesn't seem to be doing the trick for me.

EDIT: Sorry, here's the code to be copied

    int lineCounter = 0;
    char* filename = argv[3];
    int fd = open(filename, O_RDONLY);
    
    //off_t size = lseek(fd, 0, SEEK_END);
    
    if (fd == -1) perror("open");

    int n;
    char buffer[BUFFSIZE];

    while ((n = read(fd, buffer, 1)) > 0) {
        write(STDOUT_FILENO, buffer, 1);
    }
    
    for (int i = 0; i < BUFFSIZE; i++) {
        
        if (buffer[i] == '\n') {
            lineCounter++;
        }
        
    }
1

There are 1 best solutions below

0
On

corrections

int lineCounter = 0;
char* filename = argv[3];
int fd = open(filename, O_RDONLY);

//off_t size = lseek(fd, 0, SEEK_END);

if (fd == -1) perror("open");

int n;
char buffer[BUFFSIZE];

while ((n = read(fd, buffer, BUFFSIZE)) > 0) { <<<=== read uoto BUFFSIZE
    write(STDOUT_FILENO, buffer, n); <<<<=== write out the same number of read bytes


    for (int i = 0; i < n; i++) { <<<<=== put line counter inside loop to read file && loop over read number of chars
    
       if (buffer[i] == '\n') {
         lineCounter++;
       }
    
     }
  }