运行上面给出的main函数报错error: expected identifier or '(' before '=' token,修正
时间: 2023-09-20 11:12:11 浏览: 304
非常抱歉,这是因为我在拼写log.h和log.c的时候出现了一些错误。在log.h中,我忘记了#include <stdlib.h>,并且在log.c中,我忘记了#include <stdio.h>。这导致编译器无法识别malloc和snprintf函数,从而导致了错误。以下是修正后的代码:
log.h
```c
#ifndef LOG_H
#define LOG_H
#include <stdio.h>
#include <stdarg.h>
#include <stdlib.h>
#include <time.h>
#define LOG_LEVEL_DEBUG 1
#define LOG_LEVEL_INFO 2
#define LOG_LEVEL_WARN 3
#define LOG_LEVEL_ERROR 4
#define MAX_LOG_SIZE 1024 * 1024 // 日志文件最大大小,单位为字节
#define MAX_LOG_FILES 10 // 最多保留的日志文件数
typedef struct {
FILE *fp;
char *filename;
int level;
long size;
} log_t;
log_t *log_create(char *filename, int level);
void log_destroy(log_t *log);
void log_write(log_t *log, int level, const char *fmt, ...);
void log_rotate(log_t *log);
#endif
```
log.c
```c
#include "log.h"
static const char *LOG_LEVEL_STR[] = {"", "DEBUG", "INFO", "WARN", "ERROR"};
log_t *log_create(char *filename, int level) {
log_t *log = (log_t *) malloc(sizeof(log_t));
if (!log) {
fprintf(stderr, "Failed to allocate memory for log\n");
return NULL;
}
log->filename = filename;
log->level = level;
log->size = 0;
log->fp = fopen(log->filename, "a");
if (!log->fp) {
fprintf(stderr, "Failed to open log file %s\n", log->filename);
free(log);
return NULL;
}
return log;
}
void log_destroy(log_t *log) {
if (log) {
if (log->fp) {
fclose(log->fp);
log->fp = NULL;
}
free(log);
}
}
void log_write(log_t *log, int level, const char *fmt, ...) {
if (log && log->fp && level >= log->level) {
va_list args;
va_start(args, fmt);
time_t t = time(NULL);
struct tm *lt = localtime(&t);
char timestamp[20];
strftime(timestamp, sizeof(timestamp), "%Y-%m-%d %H:%M:%S", lt);
fprintf(log->fp, "[%s] [%s] ", timestamp, LOG_LEVEL_STR[level]);
vfprintf(log->fp, fmt, args);
fprintf(log->fp, "\n");
log->size = ftell(log->fp);
va_end(args);
if (log->size >= MAX_LOG_SIZE) {
log_rotate(log);
}
}
}
void log_rotate(log_t *log) {
if (log) {
fclose(log->fp);
log->fp = NULL;
char new_filename[100];
snprintf(new_filename, sizeof(new_filename), "%s.%d", log->filename, 1);
remove(new_filename);
for (int i = MAX_LOG_FILES - 1; i >= 1; i--) {
char old_filename[100], new_filename[100];
snprintf(old_filename, sizeof(old_filename), "%s.%d", log->filename, i - 1);
snprintf(new_filename, sizeof(new_filename), "%s.%d", log->filename, i);
remove(new_filename);
rename(old_filename, new_filename);
}
rename(log->filename, new_filename);
log->fp = fopen(log->filename, "a");
log->size = 0;
}
}
```
main.c
```c
#include "log.h"
int main() {
log_t *log = log_create("test.log", LOG_LEVEL_DEBUG);
if (!log) {
return 1;
}
for (int i = 0; i < 100000; i++) {
log_write(log, LOG_LEVEL_INFO, "This is a log message %d", i);
}
log_destroy(log);
return 0;
}
```
请尝试运行这个修正后的程序,看看是否成功运行了。
阅读全文