To assert and print the __FILE__ and __LINE__ macros to a log file in C, you can use the following code:

#include <stdio.h>

#define LOG_FILE "log.txt"

#define ASSERT(condition) \
    do { \
        if (!(condition)) { \
            FILE* log = fopen(LOG_FILE, "a"); \
            fprintf(log, "Assertion failed: %s\n", #condition); \
            fprintf(log, "File: %s\n", __FILE__); \
            fprintf(log, "Line: %d\n\n", __LINE__); \
            fclose(log); \
            exit(1); \
        } \
    } while (0)

int main() {
    int x = 5;
    ASSERT(x == 10);

    return 0;
}

In this example, the ASSERT macro is defined to check a condition. If the condition is false, it opens the log file in append mode ("a"), writes the assertion failure message along with __FILE__ and __LINE__ values, and then closes the file. Finally, it exits the program with a status of 1 to indicate an assertion failure.

You can customize the log file name by modifying the LOG_FILE macro

C assert print __FILE__ __LINE__ to log file

原文地址: https://www.cveoy.top/t/topic/ifO1 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录