cocoa - C: fscanf and character/string size -


i parsing text (css) file using fscanf. basic goal simple; want pull out matches pattern:

@import "some/file/somewhere.css";

so i'm using fscanf, telling read , discard '@' character , store until reaches ';' character. here's function this:

char* readdelimitedsectionaschar(file *file) { char buffer[4096];  int charsread; {     fscanf(file, "%*[^@] %[^;]", buffer, &charsread);  } while(charsread == 4095);  char *ptr = buffer; return ptr; } 

i've created buffer should able hold 4095 characters, understand it. however, i'm discovering not case. if have file contains matching string that's long, this:

@import "some/really/really/really/long/file/path/to/a/file";

that gets truncated 31 characters using buffer of char[4096]. (if use printf check value of buffer, find string cut short.)

if increase buffer size, more of string included. under impression 1 character takes 1 byte (though aware affected encoding). trying understand what's going on here.

ideally, i'd able set buffer large needs "on fly" --- is, have fscanf create buffer big enough store string. can done? (i know of %as flag gnu, mac application os 10.5/10.6 , i'm unsure if work on platform.)

the main problem have you're returning pointer local buffer on stack, dangling (and overwritten next call make). have potential buffer overflow. mention 'a' option, lot, unfortunately gnu extension isn't available.

second, have option scanf, &charsread never written there's no % in format string. charsread random garbage -- means loop (probably) run once, or (rarely) loop forever. try like

char* readdelimitedsectionaschar(file *file) {     char buffer[4096], term[2] = "", *rv = 0;     int len = 0;      fscanf(file, "%*[^@]");     while (term[0] != ';' && !feof(file)) {         if (fscanf(file, "%4095[^;]%1[;]", buffer, term) > 0) {             int read = strlen(buffer);             rv = rv ? realloc(rv, len+read+1) : malloc(read+1);             strcpy(rv+len, buffer);             len += read;         }     }     return rv; } 

this still broken in misbehave if run out of memory (which can happen if feed huge malformed file @ in beginning , no ;),


Comments

Popular posts from this blog

c++ - Convert big endian to little endian when reading from a binary file -

C#: Application without a window or taskbar item (background app) that can still use Console.WriteLine() -

unicode - Are email addresses allowed to contain non-alphanumeric characters? -