簡體   English   中英

將c中的調試消息寫入文件?

[英]write debug messages in c to a file?

如何將調試消息寫入文件?

我在用:

void printLog(const char* mylog)
{
  #ifdef DEBUG

  FILE* pFile = fopen("mylog.txt", "a");
  fprintf(pFile, "%s\n",mylog);
  fclose(pFile);

  #endif

}

但是如何編寫命令以進行調試?

編輯:

我的意思是,就像我在android中所知,你說的是Log.i("MyActivity", "MyClass.getView() — get item number " + position);

我可以在文件中寫一些類似的東西嗎? 變量可能,錯誤等。

我正在使用: gcc -g -DEBUG -o myexec myfile.c

如果你想要做的格式,你可以使用vfprintf()這就像printf() ,但打印到文件中,並用“包裝”參數:

void printLog(const char *fmt, ...)
{
#ifdef DEBUG
  FILE* pFile = fopen("mylog.txt", "a");
  if(pFile != NULL)
  {
   va_list args;
   va_start(args, fmt);
   vfprintf(pFile, fmt, args);
   va_end(args);
   fclose(pFile);
  }
#endif
}

然后你可以這樣使用:

printLog("you have %d attempts left", numAttempts);

管他呢。

您也可以為實際調用#define一個宏,然后將其全部編譯出來。 如上所述,調用將保留,但被調用的函數將變為空。 聰明的編譯器可能會優化這些調用,但您永遠無法確定。

假設C99,這樣的宏可能如下所示:

#if defined DEBUG
#define LOG(fmt, ...)    printLog(fmt, __VA_ARGS__);
#else
#define LOG(fmt, ...)    /* empty when debugging disabled */
#endif

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM