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 &
vfs_stat
is an option to do it.
Below is an example:
#include <linux/fs.h>
#include <linux/uaccess.h>
#include <linux/slab.h>
#include <linux/stat.h>
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.
The call to this function changes depending on which kernel version you are using. The two argument version was introduced somewhere between 3.8 and 3.9. So if you are using kernel 3.8 or before, you need the "three arguments", and 3.9 onwards, you need two arguments.
If you really want to do this in kernel mode, on an older kernel than 3.9, you may be better off using the vfs_fstat or vfs_stat
However, dealing with files inside the kernel is frowned upon, and you may want to consider if there isn't a BETTER alternative - for example, if you want to load some file-stuff into the memory of a board that is on your system, you could load the file in a user-mode process, and then pass the loaded parts into the kernel via some private IOCTL type function. This is much more "kernel friendly", and if you are planning on ever trying to get your driver/module included in the overall kernel source code, you probably NEED to do this.