您的位置主页 > 编程专区 > C > 一份c/c++写日志到处都能用的代码

一份c/c++写日志到处都能用的代码

2010-05-05    文章来源:互联网    浏览次数:1382     分享文章
C代码
  1. #include "stdafx.h"
  2. #include <stdio.h>
  3. #include <time.h>
  4.  
  5. #define DEBUG_LOG( str ) log_append_to_file("c:\\test.txt", str,__FILE__,__LINE__ );  
  6.  
  7. void log_append_to_file(char* filename,char* str,char* sourceFile,int fileLine)
  8. {
  9.     time_t t;
  10.     time(&t);
  11.     struct tm* tp= localtime(&t);
  12.     printf("%x\n",tp);
  13.     char now_str[100];
  14.     strftime(now_str, 100, "%Y-%m-%d %H:%M:%S", tp);
  15.  
  16.     FILE *fo;
  17.     fo = fopen(filename, "a");
  18.     if (fo == 0) {  
  19.         return;
  20.     }
  21.  
  22.     fprintf(fo, "%s %s(:%d):%s\r\n",now_str,sourceFile,fileLine, str);
  23.     fclose(fo);
  24. }
  25.  
  26. int main(int argc, char **argv)
  27. {
  28. /*********************define******************/
  29.  
  30.     DEBUG_LOG("test");
  31.     printf("Hello World!\n");
  32.     return 0;

 

C++代码
  1. #include <time.h>
  2. #include <stdio.h>
  3. #include <string.h>
  4.  
  5. #ifndef HYP_COMMON_INLINE_H
  6.     #define HYP_COMMON_INLINE_H
  7.  
  8. #define DEBUG_LOG( str ) printf( "%s(:%d):%s",__FILE__,__LINE__, str );
  9.  
  10. struct SpeedMardData
  11. {
  12.     time_t startT;
  13. };
  14.  
  15. static void fatal(char* message);
  16. static void* xmalloc(size_t size);
  17. static void SpeedMard_Start(struct SpeedMardData* data);
  18. static void SpeedMard_stopAndPrint(struct SpeedMardData data,int testCount);
  19.  
  20. inline void fatal(char* message){
  21.     printf("fatal:%s \n",message);
  22.     exit(0);
  23. }
  24.  
  25. inline void* xmalloc(size_t size) {
  26.     register void *value = malloc(size);
  27.     if (value == 0)
  28.         fatal("virtual memory exhausted");
  29.     return value;
  30. }
  31.  
  32. inline void SpeedMard_Start(struct SpeedMardData* data)
  33. {
  34.     data->startT =  time(NULL);
  35. }
  36.  
  37. inline void SpeedMard_stopAndPrint(struct SpeedMardData data,int testCount)
  38. {
  39.     time_t now = time(NULL);
  40.     printf("now:%d \n",(int)now);
  41.     printf("data.startT:%d \n",(int)data.startT);
  42.     double dTime = difftime (now, data.startT);
  43.     printf("dTime:%f speed %f times/sec \n", dTime,(double)testCount / dTime);
  44. }
  45.  
  46. inline void debug_append(const char* filename,const char* str)
  47. {
  48.      FILE *fp;
  49.      fp=fopen(filename,"a");
  50.      fwrite(str,sizeof(char),strlen(str),fp);
  51.      fwrite("\n",sizeof(char),1,fp);
  52.      fclose(fp);
  53. }

 

  • 上一篇:C 程序优化 小结
  • 下一篇:memset用法详解
  • 文章评论(查看全部)

    昵 称 *
    电子邮箱 *
    网 址      8 + 5 = ?