Linux内核写入数据到文件,将数组序列化到文件

内核已经提供了相应函数。实例如下:

#include <linux/module.h>
#include <linux/init.h>
#include <linux/fs.h>
#include <linux/uaccess.h>
static char buf[] ="hello. \n";
static char buf1[100];
static u32 inflight_x[100] = {1,2,3,4,5,6,1,2,3,4,5,6,1,2,3,4,5,6,1,2,3,4,5,6,};
int __init hello_init(void)
{
    struct file *fp;
    loff_t pos;
    ssize_t res = 0;
    printk("hello enter/n");
    fp = filp_open("/.../kernel_file.txt",O_RDWR | O_CREAT,0777);
    if (IS_ERR(fp)){
        printk("create file error/n");
        return -1;
    }

    for (i=0;i<24;++i) {
        len = sprintf(my_buf, "%u ", inflight_y[i]);
        my_buf += len;

    }
    
    pos = 0;
    res = kernel_write(fp, buf, sizeof(buf), &pos);
    if (res < 0) {
         printk("kernel_write error: %d\n", res);
         return 0;
    }
   
    pos = 0;
    res = kernel_read(fp, buf1, sizeof(buf), &pos);
    if (res < 0) {
         printk("kernel_write error: %d\n", res);
         return 0;
    }
    printk("read: %s/n",buf1);

    filp_close(fp,NULL);

    return 0;
}
void __exit hello_exit(void)
{
    printk("hello exit/n");
}
 
module_init(hello_init);
module_exit(hello_exit);
 
MODULE_LICENSE("GPL");
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值