title: Coping a Line from a File to Array (C)
body: <p>Given a file with information sorted by line, I'm asked to write a program to store each line in a string. </p>
  
  <pre><code>This is the first line. 
  This is the second line. 
  This is the third line.
  This is the fourth line.
  </code></pre>
  
  <p>My code is as follows:</p>
  
  <pre><code>#include&lt;stdio.h&gt;
  #include&lt;stdlib.h&gt;
  #include&lt;string.h&gt;
  #define MAX 70
  #define NLine 4
  int main()
  {
      FILE *arq;
      char line[MAX];
      char *eof;
      char name[20];
      char *nline[NLine];
      int i;
      printf("\nGive me the name of the file: ");
      fgets(name, 20 , stdin);
      arq = fopen(name, "r");
      while( ( eof = fgets(line, MAX, arq ) )!= NULL )
          {
              nline[i] = strdup(eof);
              i++;
          }
      printf("\n");
      for(i = 0; i &lt; NLine; i++)
          printf("%s", nline[i]);
      for(i = 0; i &lt; NLine; i++)
          free( nline[i] );
      fclose(arq);
      return 0;
  }
  </code></pre>
  
  <p>My output is a segmentation fault; but when I substitute <code>arq = fopen(name, "r");</code> for <code>arq = fopen("test.txt", "r");</code> the program runs perfectly. I execute <code>gdb</code> and it has returned </p>
  
  <pre><code>Program received signal SIGSEGV, Segmentation fault.
  0x00007ffff7a7ea2b in fgets () from /lib64/libc.so.6
  </code></pre>
  
  <p>Is it wrong to call <code>fopen</code> with an array of strings as a parameter, or did I do something wrong in the program?</p>
  
  <p>Also I would like to know how the part </p>
  
  <pre><code>    while( ( eof = fgets(line, MAX, arq ) )!= NULL )
          {
              nline[i] = strdup(eof);
              i++;
          }
  </code></pre>
  
  <p>works. I just saw the code in this <a href="https://stackoverflow.com/questions/7920932/how-to-use-fgets-and-store-every-line-of-a-file-using-an-array-of-char-pointer">question</a> and managed it to work; but I did not understand how the function read another line instead of keeping reading the same line, for there is no apparent change in how the <code>eof</code> is read from the file.</p>