logo

Função snprintf() em C

Nesta seção, discutiremos a função snprintf() na linguagem de programação C. O snprintf é uma função de biblioteca predefinida do arquivo de cabeçalho stdio.h, que redireciona a saída da função printf() padrão para outros buffers.

A função snprint() é usada para formatar as strings fornecidas em uma série de caracteres ou valores na área do buffer. A função snprintf() contém um argumento 'n' que representa o número máximo de caracteres, incluindo o caractere nulo, armazenados na área de buffer.

A função snprintf também retorna o número de caracteres inseridos ou gravados no buffer. No entanto, esses caracteres são retornados ou exibidos pela função printf() na instrução print ou caracteres no arquivo de cabeçalho stdout.

Função snprintf() em C

Nota: A função snprintf() insere um caractere nulo no final da saída resultante que também é contado como o tamanho do buffer. Além disso, o buffer é um array que armazena apenas elementos do tipo caractere, não no tipo string.

Sintaxe da função snprintf() em C

A seguir está a sintaxe da função snprintf() na linguagem de programação c.

 int snprintf (char *str, size_t size, const char *format, ?); 

Parâmetros:

str : É um buffer de matriz de tipo de caractere.

tamanho : define o número máximo de caracteres que podem ser armazenados no buffer.

formatar : Na linguagem C, a string define um formato que contém o mesmo tipo de especificações que a função printf() define no arquivo de cabeçalho stdio.h.

…: É um parâmetro ou argumento opcional (…).

Valores de retorno:

A função snprintf() retorna o número de caracteres ou valores que foram escritos ou armazenados para um buffer suficientemente grande sem incluir o caractere de terminação nulo. E se os caracteres escritos forem maiores que o tamanho do buffer, ele retornará um valor negativo. E se o tamanho do buffer for muito pequeno, a string fornecida será truncada ou reduzida ao tamanho do buffer.

Exemplo 1: Programa para demonstrar a função snprintf() em C

Vamos criar um programa para verificar o tamanho do buffer e retornar o número de caracteres inseridos no buffer usando a função snprintf() em C.

 /* create an example to use the snprintf function in c. */ #include #include int main () { // declare and initialize the char variable char *r = 'Javatpoint.com'; char buf[100]; // define the size of character type buffer /* use the snprintf() function to return the no. of character founded in the buffer area */ int n = snprintf (buf, 34, '%s 
', r); // 34 represents the size of buffer to store max characters // display the string stored in the buffer and count each character of the buffer area. printf (' The given string is: %s 
 Count the stored character: %d 
', buf, n); return 0; } 

Quando executamos o programa acima, ele produz a saída fornecida na tela do console.

 The given string is: Javatpoint.com Count the stored character: 16 

2eexecução

 The given string is: Javatpoint.com Count the stored character: -1 

Agora reduzimos o caractere máximo de entrada de 34 para 14 e, desta vez, ele retorna um número negativo, indicando que o tamanho do buffer é menor que a string fornecida.

Exemplo 2: Programa para usar a função snprintf() em C

Vamos criar um exemplo para inserir o caractere no buffer e retornar do mesmo usando a função snprintf() na linguagem de programação C.

 #include #include int main () { char buf[200]; // define the size of character type buffer int ret_val, buf_size = 55; char name[] = &apos;David&apos;; // define string int age = 19; // use the snprintf() function to return the no. of character found in buffer area ret_val = snprintf (buf, buf_size, &apos;Hello friend, My name is %s, and I am %d years old.&apos;, name, age); /* check ret_value should be greater than 0 and less than the size of the buffer (buf_size). */ if ( ret_val &gt; 0 &amp;&amp; ret_val <buf_size) { printf (' buffer is written successfully! 
 '); %s
', buf); no. of characters read: %d', ret_val); } else not completely filled or written. %s 
', the return value: 0; < pre> <p> <strong>When we execute the above program, it produces the given output on the console screen.</strong> </p> <pre> Buffer is written successfully! Hello friend, My name is David, and I am 19 years old. No. of characters read: 53 </pre> <p>In the above program, we declared the character type buffer buf[200], and the buf_size variable can insert the maximum characters is 55. If the given statement is in the defined range, the snprintf() function returns the total no. of characters read from the buffer. </p> <p> <strong>2<sup>nd</sup> execution</strong> </p> <pre> Buffer is not completely filled or written. Hello friend, My name is David and The return value: -1 </pre> <p>When we define the buf_size as 35, the given statement is automatically truncated by the snprintf() function that returns a negative number (-1) and displays &apos;Buffer is not completely filled or written&apos;.</p> <hr></buf_size)>

No programa acima, declaramos o tipo de caractere buffer buf[200], e a variável buf_size pode inserir o máximo de caracteres é 55. Se a instrução fornecida estiver no intervalo definido, a função snprintf() retorna o número total. de caracteres lidos do buffer.

2eexecução

 Buffer is not completely filled or written. Hello friend, My name is David and The return value: -1 

Quando definimos buf_size como 35, a instrução fornecida é automaticamente truncada pela função snprintf() que retorna um número negativo (-1) e exibe 'Buffer não está completamente preenchido ou escrito'.