Note that there are some explanatory texts on larger screens.

plurals
  1. POC: fscanf and character/string size
    text
    copied!<p>I am parsing a text (css) file using fscanf. The basic goal is simple; I want to pull out anything that matches this pattern:</p> <p>@import "some/file/somewhere.css";</p> <p>So I'm using fscanf, telling it to read and discard everything up to a '@' character and then store everything until it reaches a ';' character. Here's the function that does this:</p> <pre><code>char* readDelimitedSectionAsChar(FILE *file) { char buffer[4096]; int charsRead; do { fscanf(file, "%*[^@] %[^;]", buffer, &amp;charsRead); } while(charsRead == 4095); char *ptr = buffer; return ptr; } </code></pre> <p>I've created a buffer that should be able to hold 4095 characters, as I understand it. However, I'm discovering that this is not the case. If I have a file that contains a matching string that's long, like this:</p> <p>@import "some/really/really/really/long/file/path/to/a/file";</p> <p>That gets truncated to 31 characters using a buffer of char[4096]. (If I use printf to check the value of buffer, I find that the string is cut short.)</p> <p>If I increase the buffer size, more of the string is included. I was under the impression that one character takes one byte (though I am aware this is affected by encoding). I am trying to understand what's going on here.</p> <p>Ideally, I'd like to be able to set the buffer as large as it needs to be "on the fly" --- that is, have fscanf just create a buffer big enough to store the string. Can this be done? (I know of the %as flag for GNU, but this is a Mac application for OS 10.5/10.6 and I'm unsure if that will work on this platform.)</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload