When you print a log in a Linux/C + + program, you may need to print an unknown number of variable parameters, so the vsnprintf function comes in handy. A simple C-program example is used to illustrate the use of the vsnprintf function to print an unknown number of parameter variables while printing the source program file name and the line number of the print function.
1 Full Program
The code is simpler, and if you need to print the content in a log file, you will also need to call the file handler function. For ease of understanding, the content is exported directly to the console. Three Places to note:
Static global variables C_filename and i_filelinenum are used to store the source program file name and the line number of the print function respectively;
The custom identifier PRINT first invokes the assignment function Get_file_line of the source program file name and the line number, and then calls the handler function of the unknown number of parameters f_vsnprintf;
Similar to the sprintf and snprintf functions, the vsnprintf adds the maximum byte (maxbytes) limit to prevent memory overflow compared to the vsprintf function.
The specific code is as follows:
The code is as follows |
Copy Code |
#include <stdio.h> #include <string.h> #include <stdarg.h> #define Filename_len 100 #define Maxline 1024 #define MaxBytes 50 static Char C_filename[filename_len]; static int i_filelinenum; Self-define a function which can print the name and line-number of the source file calling it. #define PRINT get_file_line (__file__, __line__); \ f_vsnprintf /** * Get the LineNum and filename of the source file. * @Para-in:p_filename:the Name of the source file. * @Para-in:i_fileline:the Line-number of the source file. */ void Get_file_line (char *p_filename, int i_fileline) { strcpy (C_filename, p_filename); I_filelinenum = I_fileline; Return } /** * Print The arguments according to the the ' the ' the ' the ' the ' the ' the ' argument '. */ void f_vsnprintf (char *fmt, ...) { Char Buf[maxline] = {0x00}; snprintf (buf, MaxBytes, "[%s:%d]", C_filename, I_filelinenum); Va_list ap; Va_start (AP, FMT); vsnprintf (Buf+strlen (BUF), Maxline, FMT, AP); Va_end (AP); strcat (buf, "\ n"); Fflush (stdout); Fputs (buf, stderr); Fflush (NULL); Return } int main (int argc, char **argv) { PRINT ("[%s]", "Hello."); PRINT ("[%s%s]", "Hello", "world."); return 0; } |