1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104
| #include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <string.h>
#define CRLF "\n"
#define VERSION_DATE "2012AUG10"
#define MANNO 1
#define ERR_MSG_MAX_LENGTH 10000
typedef struct
{
char name[255];
char birth_date[255];
}SOMEONE;
typedef struct
{
char name[255];
int version;
}APPLICATION;
SOMEONE *him;
APPLICATION *that;
FILE *fplog = NULL;
int file_exists(char *filename)
{
FILE *fp;
if ((fp = fopen(filename, "r")) == NULL)
return 0;
else
{
fclose(fp);
return 1;
}
}
int msg_handler( long code, const char *format, va_list args)
{
char fmt[ERR_MSG_MAX_LENGTH];
int ret = 0;
va_list args_copy;
va_copy(args_copy, args);
if (code > 0) /*print on the console if code >0*/
{
vprintf(format, args_copy);
va_end(args_copy);
}
/*whatever print to file*/
sprintf(fmt, "%d\t%s" CRLF, code, format);
va_copy(args_copy, args);
vfprintf(fplog,fmt, args_copy);
va_end(args_copy);
ret |= 2;
return ret;
}
void trc_msg( long code, const char *format, ...)
{
int ret;
va_list args;
va_start(args, format);
ret = msg_handler(code, format, args);
va_end(args);
}
int main()
{
int i = 0;
if (file_exists("./test.log"))
fplog = fopen("./test.log", "a+");
else
{
fplog = fopen("./test.log", "w");
if (fplog)
fprintf(fplog, "CODE\tDESCRIPTION" CRLF);
}
him = calloc(1, sizeof(SOMEONE));
that = calloc(1, sizeof(APPLICATION));
for (i=0;i<2;i++)
{
sprintf(him->name,"robot%d", i);
strcpy(him->birth_date, VERSION_DATE);
strcpy(that->name,"Super2000");
that->version = 1;
trc_msg( i, "Mr: %s was created on %s using application: %s[%d]", him->name, him->birth_date, that->name, that->version);
}
fclose(fplog);
free(him);
free(that);
return 0;
} |
Partager