The snprintf()
function of the default library stdio.h
is able to calculate the size needed to accommodate the formatted string. The secret is to pass a buffer NULL
, with size 0
, causing snprintf()
to return the amount of bytes needed to accommodate the formatted string, see:
size_t tam = snprintf( NULL, 0, "makeblastdb -in %s -dbtype prot -out SASBT_BLASTDB > /dev/null", one_rawreference );
Here's an example (tested) based on your need:
#include <stdio.h>
#include <stdlib.h>
char * formatar_comando( char const * one_rawreference )
{
/* String de formatacao */
const char * fmt = "makeblastdb -in %s -dbtype prot -out SASBT_BLASTDB > /dev/null";
/* Calcula tamanho necessario para acomodar a string formatada */
size_t tam = snprintf( NULL, 0, fmt, one_rawreference );
/* Aloca a memoria necessaria para acomodar a string formatada */
char * output = malloc( tam + 1 );
/* Formata string efetivamente */
sprintf( output, fmt, one_rawreference );
/* Retorna */
return output;
}
int main( void )
{
/* Formatacao do comando em vetor dinamico */
char * cmd = formatar_comando( "foobar" );
/* Exibe o comando que sera executado */
printf("Comando: %s\n", cmd );
/* Execucao do comando */
system(cmd);
/* Libera memoria do vetor dinamico usada para formatacao */
free(cmd);
/* Sucesso */
return 0;
}
The execution of your command can be encapsulated completely within a single function, which would be able to allocate only the memory required for formatting the string, see:
#include <stdio.h>
#include <stdlib.h>
int executar_makeblastdb( char const * one_rawreference )
{
/* String de formatacao */
const char * fmt = "makeblastdb -in %s -dbtype prot -out SASBT_BLASTDB > /dev/null";
/* Calcula tamanho necessario para acomodar a string formatada */
size_t tam = snprintf( NULL, 0, fmt, one_rawreference );
/* Aloca a memoria necessaria para acomodar a string formatada */
char * cmd = malloc( tam + 1 );
/* Formata string */
sprintf( cmd, fmt, one_rawreference );
/* Executa comando */
int ret = system(cmd);
/* Libera a memoria ocupada */
free(cmd);
/* Retorna status da execucao do comando */
return ret;
}
int main( void )
{
int ret = executar_makeblastdb( "foobar" );
if( ret < 0 )
{
printf("Erro executando comando.\n");
return 1;
}
printf("Comando executado com sucesso.\n");
return 0;
}