How do you get the size of a file in the linux kernel?

前端 未结 2 1857
挽巷
挽巷 2021-01-22 22:10

I found this link (http://www.spinics.net/lists/newbies/msg41016.html) and have been looking into doing just that. So I wrote code in a kernel module:

#include &         


        
2条回答
  •  一向
    一向 (楼主)
    2021-01-22 22:47

    vfs_stat is an option to do it.

    Below is an example:

    #include 
    #include 
    #include 
    #include 
    
    static char *load_file(char* filename, int *input_size)
    {
            struct kstat *stat;
            struct file *fp;
            mm_segment_t fs;
            loff_t pos = 0;
            char *buf;
    
            fp = filp_open(filename, O_RDWR, 0644);
                    if (IS_ERR(fp)) {
                            printk("Open file error!\n");
                            return ERR_PTR(-ENOENT);
            }
    
            fs = get_fs();
            set_fs(KERNEL_DS);
            
            stat =(struct kstat *) kmalloc(sizeof(struct kstat), GFP_KERNEL);
            if (!stat)
                    return ERR_PTR(-ENOMEM);
    
            vfs_stat(filename, stat);
            *input_size = stat->size;
    
            buf = kmalloc(*input_size, GFP_KERNEL);
                    if (!buf) {
                            kfree(stat);
                            printk("malloc input buf error!\n");
                            return ERR_PTR(-ENOMEM);
                    }
            kernel_read(fp, buf, *input_size, &pos);
    
            filp_close(fp, NULL);
            set_fs(fs);
            kfree(stat);
            return buf;
    }
    

    Since the size is not known, so we need to kmalloc inside the function, thus the buf need to kfree later when not use any longer.

提交回复
热议问题