Sileno Brito
Sileno Brito

Reputation: 459

How create a FILE* from char * without create a temporary file

I'm creating a program using lex and yacc to parse text, but i need create a parser of various content. I don't wish use the stdin, if i using FILE *yyin to specify the input, i can change the source. I need can call the function from library parse (created with lex file and yacc file) to parse this content and receive a result.

/**
* This i don't know is possible, receive a char * and return a FILE*
*/
FILE *function_parse_to_file(char* text){
    FILE *fp = NULL;
    /**
    * is really necessary create a temporary file with content text?
    */

    return fp
}
/**
* I need call from other library or application
*/
char *function_parse_from_lex(char* text){
    yyin = function_parse_to_file(text);
    init(); 
    yyparse(); 
    fclose(yyin); 
}

Upvotes: 0

Views: 249

Answers (3)

William Pursell
William Pursell

Reputation: 212298

You really haven't stated your question clearly, but I am going to assume you want to create a FILE * which will return the contents of the string pointed to by the char * when data is read from it. You could simply create a pipe and then invoke fdopen on the read side. It is a bit dangerous to just write the data into the write side, since the write might block and lead to a deadlock, but you can certainly fork a child and have the child write the data into the pipe.

On the other hand, there's no real reason not to create a temporary file. Assuming you are going to unlink the file after you read it, there's very little chance of the data ever going to disk (the OS will keep it in memory) If you're really concerned to can use a path on a ram disk.

Upvotes: 0

Valeri Atamaniouk
Valeri Atamaniouk

Reputation: 5163

You can define YY_INPUT macro with three arguments: buffer, result, max_size, where:

  • buffer - input with buffer where to read data,
  • result - output to store number of bytes read
  • max_size - input with buffer size

Just include the macro definition in your Lex file using header or inline and it will be used instead of fread(...)

Upvotes: 1

Fred Foo
Fred Foo

Reputation: 363627

On a POSIX-2008-compliant system (and on Linux), you can use fmemopen to get a FILE* handle on an in-memory buffer.

Upvotes: 2

Related Questions