c++low-level-io

Why is this program only printing out the first line?


Could someone explain why the following code is only printing out the first line as opposed to the first 3 lines? I went through the for-loop manually on a sheet of paper, and I thought that it would increment by 3 lines, but my logic must be off somewhere.

#include <cstdlib>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <iostream>
using namespace std;
#define BUFFSIZE 1024

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

 char buf[BUFFSIZE];
  int numRead = 0;
  int newlinePosition = -1;

  numRead = read(fd, buf, BUFFSIZE);
for(int i = 0; i < numRead && newlinePosition < 3; i++) {
    if(buf[i] == '\n') {
      newlinePosition = i;
      if(i + 1 < numRead) {
        newlinePosition += 1;
      }
    }
  }

  if(newlinePosition < 0) {
    newlinePosition = numRead;
  }

  write(STDOUT_FILENO, buf, newlinePosition);

Solution

  • if there are 30 words in a line. After that a newline then newLinePosition will be 30 right ? so there will be no second line as 30 > 3.

    for(int i = 0; i < numRead && newlinePosition < 3; i++) {
            if(buf[i] == '\n') {
              newlinePosition++;
              if(i + 1 < numRead) {
                newlinePosition += 1;
              }
            }
          }
    

    though i am not sure why i+1 < numRead is used. But it should help you.