title: Specifying the maximum string length to scanf dynamically in C (like "%*s" in printf)
body: <p>I can specify the maximum amount of characters for <code>scanf</code> to read to a <code>buffer</code> using this technique:</p>
  
  <pre><code>char buffer[64];
  
  /* Read one line of text to buffer. */
  scanf("%63[^\n]", buffer);
  </code></pre>
  
  <p>But what if we do not know the buffer length when we write the code? What if it is the parameter of a function?</p>
  
  <pre><code>void function(FILE *file, size_t n, char buffer[n])
  {
      /* ... */
      fscanf(file, "%[^\n]", buffer); /* WHAT NOW? */
  }
  </code></pre>
  
  <p>This code is <strong>vulnerable to buffer overflows</strong> as <code>fscanf</code> does not know how big the buffer is.</p>
  
  <p>I remember seeing this before and started to think that it was the solution to the problem:</p>
  
  <pre><code>fscanf(file, "%*[^\n]", n, buffer);
  </code></pre>
  
  <p>My first thought was that the <code>*</code> in <code>"%*[*^\n]"</code> meant that the maximum string size is passed an argument (in this case <code>n</code>). This is the meaning of the <code>*</code> in <code>printf</code>.</p>
  
  <p>When I checked the documentation for <code>scanf</code> I found out that it means that <code>scanf</code> should discard the result of <code>[^\n]</code>.</p>
  
  <p>This left me somewhat disappointed as I think that it would be a very useful feature to be able to pass the buffer size dynamically for <code>scanf</code>.</p>
  
  <p>Is there any way I can pass the buffer size to <code>scanf</code> dynamically?</p>