vsnprintf字符串格式化输出实例:日志中打印程序名和行号
/**
* @FileName vsnprintf_name_line.c
* @Describe A simple example for using vsnprintf to print the name and line-num of source file in linux.
* @Author vfhky 2016-03-13 23:28 https://typecodes.com/cseries/vsnprintffilenameline.html
* @Compile gcc vsnprintf_name_line.c -o vsnprintf_name_line
*/
#include
#include
#include
#define FILENAME_LEN 100
#define MAXLINE 1024
#define MAXBYTES 50
static char c_FileNameFILENAME_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 first argument, name as fmt.
*/
void F_vsnprintf( char *fmt, ... )
{
char bufMAXLINE = {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;
}