La risposta accettata non è corretta. Ciò causerà perdite di memoria.
Internamente, yy_scan_string chiama yy_scan_bytes che, a sua volta, chiama yy_scan_buffer.
yy_scan_bytes alloca la memoria per una COPIA del buffer di input.
yy_scan_buffer funziona direttamente sul buffer fornito.
Con tutte e tre le forme, è necessario chiamare yy_delete_buffer per liberare le informazioni di stato del buffer flessibile (YY_BUFFER_STATE).
Tuttavia, con yy_scan_buffer, si evita l'allocazione interna/copia/free del buffer interno.
Il prototipo di yy_scan_buffer NON accetta un const char * e NON DEVE aspettarsi che il contenuto rimanga invariato.
Se si è allocata memoria per contenere la stringa, si ha la responsabilità di liberarla DOPO che si chiama yy_delete_buffer.
Inoltre, non dimenticare di fare in modo che yywrap restituisca 1 (non zero) quando si analizza SOLO questa stringa.
Di seguito è riportato un esempio COMPLETO.
%%
<<EOF>> return 0;
. return 1;
%%
int yywrap()
{
return (1);
}
int main(int argc, const char* const argv[])
{
FILE* fileHandle = fopen(argv[1], "rb");
if (fileHandle == NULL) {
perror("fopen");
return (EXIT_FAILURE);
}
fseek(fileHandle, 0, SEEK_END);
long fileSize = ftell(fileHandle);
fseek(fileHandle, 0, SEEK_SET);
// When using yy_scan_bytes, do not add 2 here ...
char *string = malloc(fileSize + 2);
fread(string, fileSize, sizeof(char), fileHandle);
fclose(fileHandle);
// Add the two NUL terminators, required by flex.
// Omit this for yy_scan_bytes(), which allocates, copies and
// apends these for us.
string[fileSize] = '\0';
string[fileSize + 1] = '\0';
// Our input file may contain NULs ('\0') so we MUST use
// yy_scan_buffer() or yy_scan_bytes(). For a normal C (NUL-
// terminated) string, we are better off using yy_scan_string() and
// letting flex manage making a copy of it so the original may be a
// const char (i.e., literal) string.
YY_BUFFER_STATE buffer = yy_scan_buffer(string, fileSize + 2);
// This is a flex source file, for yacc/bison call yyparse()
// here instead ...
int token;
do {
token = yylex(); // MAY modify the contents of the 'string'.
} while (token != 0);
// After flex is done, tell it to release the memory it allocated.
yy_delete_buffer(buffer);
// And now we can release our (now dirty) buffer.
free(string);
return (EXIT_SUCCESS);
}
Hey dfa (che è adatto considerando il suo flex) potresti aggiungere qualcosa sul requisito del doppio zero ? –
Probabilmente la main sample fallirà, poiché 'yy_scan_buffer' richiede un buffer scrivibile (modifica temporaneamente il buffer, inserisce NUL per terminare' yytext' e quindi ripristina i caratteri originali), E richiede DUE terminando byte NUL. –
A proposito, nel mio programma C++, dovevo dichiarare 'yy_scan_bytes' con un parametro' size_t len' per evitare errori di linker. – coldfix