Read_File_From_Kernel_Module

 
If you want to read a file from a kernel module, you probably missed something
in your design! Anyway, most of the things that I did so far were for the heck
of it...so here it is!


 1  #define __KERNEL__
 2  #define MODULE
 3  #include <linux/module.h>

 4  #include <asm/uaccess.h>
 5  #include <linux/mm.h>
 6
 7  int init_module(){

 8
 9
10          ReadFile("/root/dingo",0);
11
12          return 0;

13  }
14
15
16  void cleanup_module(){
17  }
18  int  ReadFile(char *Filename, int StartPos)

19  {
20          struct file     *filp;
21          char            *Buffer;
22          mm_segment_t    oldfs;
23          int             BytesRead;

24
25          Buffer = (char *)kmalloc(4096,GFP_KERNEL);
26          if (Buffer==NULL)

27          return;
28
29          //filp = filp_open(Filename,O_RDWR | O_CREAT,0644);
30          filp = filp_open(Filename,O_RDWR | O_CREAT,0);
31          if (IS_ERR(filp)||(filp==NULL))

32          return -1;  /* Or do something else */
33
34          if (filp->f_op->read==NULL)

35          return;
36
37          filp->f_pos = StartPos;
38          oldfs = get_fs();
39          set_fs(KERNEL_DS);
40          BytesRead = filp->f_op->read(filp,Buffer,4096,&filp->f_pos);

41          Buffer[BytesRead]=0;
42          printk("NUMBER OF ABRAKADABRA BYTES=%d %s\n",BytesRead,Buffer);
43          set_fs(oldfs);

44
45          /* Close the file */
46          filp_close(filp,NULL);
47
48          return 0;

49
50  }