如何将调试消息写入文件?
我正在使用:
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
答案 0 :(得分:2)
如果你想进行格式化,你可以使用类似printf()
的{{3}},但是打印到一个文件并使用" wrap"参数:
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