title: How to read a file one line at a time and pass each line to a struct in C?
body: <p>I am trying to create two methods in C. One method that opens a file and reads it one line at a time each time it's called, the other method takes in a line and puts certain information from that line into a struct. I have the struct method mostly working but I cannot figure out how to make the first method only read one line at a time and pass it. I have only been successful in making it read the entire file all at once with a buffer. My current work is below:</p>
  
  <pre><code>//First method
  char * GimmeALine(int FD){
  
  static char buf[BUFFSIZE];
  
  ssize_t nchr = 0;
  ssize_t idx = 0;
  off_t *offset = 0;
  char *p = NULL;
  ssize_t *len;
  
  if((nchr = lseek(FD, *offset, SEEK_SET)) !=-1)
    nchr = read(FD, buf, sizeof(buf));
  (close(FD));
  
  if(nchr == -1){
      err_sys("File read error");
  }
  
    if(nchr == 0) return NULL;
  
    p = buf;
    while(idx &lt; nchr &amp;&amp; *p != '\n') p++, idx++;
    *p = 0;
  
    if(idx == nchr){
      *offset += nchr;
  
      return NULL;
      }
  
     *offset += idx +1;
     *len = idx;
     return buf;
  }
  //Main used for testing
  #include &lt;stdio.h&gt;
  #include &lt;sys/types.h&gt;
  #include &lt;sys/stat.h&gt;
  #include &lt;fcntl.h&gt;
  #define BUFFSIZE 1024
  
  //Prototypes
  char* GimmeALine(int FD);
  struct Country *FillAStruct(char * Line);
  
  int main(int argc, char* argv[])
  {  
  
    int file;
    char* line;
    file = open("AllCountries.dat", O_RDONLY);  //Opens the in file
    if(file == -1){
      err_sys("File open error");
    }
  
     GimmeALine(file);
     close(file);
    return 0;
  }
  </code></pre>
  
  <p>As part of the assignment, we were required to use the open(), read(), and close() functions instead of their easier f counterparts. Any help is appreciated.</p>