utils.h 文件:
#ifndef __UTILS_H__ #define __UTILS_H__ void a2f(const char *s, ...); #endif
utils.c 文件:
#include <linux/fs.h> #include <asm/segment.h> #include <asm/uaccess.h> #include <linux/buffer_head.h> #include <linux/string.h> #include "utils.h" #define FILE_PATH "/hzh" static struct file *fp; static int open_it() { if (fp) return 0; mm_segment_t oldfs; int err = 0; oldfs = get_fs(); set_fs(get_ds()); fp = filp_open(FILE_PATH, O_CREAT|O_RDWR|O_APPEND, 0); // 以追加方式写入文件 set_fs(oldfs); if (IS_ERR(fp)) { err = PTR_ERR(fp); return 1; } return 0; } static void close_it() { if (!fp) return; filp_close(fp, 0); fp = 0; } static int read_it(unsigned long long offset, unsigned char *data, unsigned int size) { if (!fp) return 0; mm_segment_t oldfs; int ret; oldfs = get_fs(); set_fs(get_ds()); ret = vfs_read(fp, data, size, &offset); set_fs(oldfs); return ret; } static int write_it(unsigned long long offset, unsigned char *data, unsigned int size) { if (!fp) return 0; mm_segment_t oldfs; int ret; oldfs = get_fs(); set_fs(get_ds()); ret = vfs_write(fp, data, size, &offset); set_fs(oldfs); return ret; } static int sync_it() { if (!fp) return 0; vfs_fsync(fp, 0); return 0; } void a2f(const char *fmt, ...) { if (open_it()) return; char print_buf[1024]; va_list args; int printed; //初始化args,使其指向可变参数的第一个参数,fmt是可变参数的前一个参数 va_start(args, fmt); printed = vsprintf(print_buf, fmt, args); va_end(args); write_it(0, print_buf, printed); sync_it(); // close_it(); }